我有一个使用Alamofire 2.0和以下init的
Swift 2.0 ApiManager类:
var manager:Manager init() { var defaultHeaders = Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders ?? [:] defaultHeaders["Authorization"] = "Bearer \(UserAccount.sharedInstance.token)" let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() configuration.HTTPAdditionalHeaders = defaultHeaders manager = Alamofire.Manager(configuration: configuration) }
功能示例:
func getMe(completion:(jsonObject: NSDictionary) -> ()) { manager.request(.GET,Constants.apiURL + "me").responseJSON { request,response,result in print(self.manager) //THIS LINE FIXES IT switch result { case .Success(let json): completion(jsonObject: json as! NSDictionary) case .Failure(let data,let error): print("Error: \(__FUNCTION__)\n",data,error) } } }
我收到的错误:
Error Domain=NSURLErrorDomain Code=-999 "cancelled"
似乎请求被取消,因为管理器正在被取消分配.添加print语句可以防止管理器被释放,然后它就可以完美地运行了.但我正在努力寻找更好的解决方案.
任何帮助,将不胜感激!
我正在遇到同样的问题,我用它来解决它
原文链接:/swift/319190.htmlclass Session { static let sharedInstance = Session() private var manager : Manager? func ApiManager()->Manager{ if let m = self.manager{ return m }else{ let defaultHeaders = ["X-Version":"Some header"] let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() configuration.HTTPAdditionalHeaders = defaultHeaders let tempmanager = Alamofire.Manager(configuration: configuration) self.manager = tempmanager return self.manager! } } }
然后我打电话给它
Session.sharedInstance.ApiManager().request(...