Resolved an issue with the Alamofire library setting Head invalid under iOS7

  • 2020-06-15 10:20:48
  • OfStack

The same code has no problem under iOS8, and iOS7 fails to fetch the data (error like Cocoa Error 3840 will be included). Tracking found that the request Head parameter setting did not work, and changed 1 compatible code according to the reference at the bottom of the text:


 code 
  private func getRequest(method: Method, _ URLString: URLStringConvertible, parameters: [String: AnyObject]? = nil) -> NSMutableURLRequest {
    let request = NSMutableURLRequest(URL: NSURL(string: URLString.URLString)!)
    request.HTTPMethod = method.rawValue
    if parameters != nil {
      request.HTTPBody = NSJSONSerialization.dataWithJSONObject(parameters!, options: nil, error: nil)
    }
    request.setValue(API_UA, forHTTPHeaderField: "User-Agent")
    request.setValue(HEADER_ACCEPT, forHTTPHeaderField: "Accept")
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    
    return request
  }

Here API_UA and HEADER_ACCEPT can be changed to their own Head parameters, using the code:


var request: Request!
    if DeviceUtils.isIOS7() {
      request = mHttpManager.request(getRequest(method, URLString, parameters: parameters))
    } else {
      request = mHttpManager.request(method, URLString , parameters: parameters, encoding: ParameterEncoding.JSON)
    }
    //request.responseJSON....

Code description:

a), mHttpManager is Manager sharedInstance, pay attention to. Don't forget to set the mHttpManager session. configuration. HTTPAdditionalHeaders, under iOS8 or help

Reference:

Setting Custom HTTP Headers in Alamofire in iOS 7 not working (reference post, try NSURLSessionConfiguration as well but it doesn't work)

Above is the Alamofire library under iOS set Head data collation, hope to help the development of IOS software students.


Related articles: