【iOS】Alamofire庫在iOS7下設置Head無效的問題



聲明  
歡迎轉載,但請保留文章原始出處:) 
博客園:http://www.cnblogs.com
農民伯伯: http://over140.cnblogs.com

 

正文

同樣的代碼在iOS8下沒有問題,iOS7就取不到數據(會包Cocoa Error 3840之類的錯誤),跟蹤發現請求Head參數設置不管用,根據文字底部的參考改了一下兼容代碼:

     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
    }

這里API_UA和HEADER_ACCEPT更改為自己的Head參數即可,使用代碼:

        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....

代碼說明:

a)、 mHttpManager就是Manager.sharedInstance,注意別忘了設置mHttpManager.session.configuration.HTTPAdditionalHeaders,在iOS8下還是管用的

 

參考:

Setting Custom HTTP Headers in Alamofire in iOS 7 not working 

(參考帖子,也嘗試設置NSURLSessionConfiguration但是沒有效果 

 

結束

繼續iOS,繼續swift,繼續遇到問題解決問題。 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM