Alamofire.request 与 manager.request - 经理不工作

Alamofire.request vs. manager.request - manager not working

编辑:问题不是关于 -999 的含义,而是为什么第一个代码片段没有出现错误,而第二个代码片段出现错误? 除了在第二个代码片段中使用 Alamofire.Manager(应该与第一个代码片段中的 Alamofire.request 相同)之外,一切都是相同的。 这是一个错误,还是我遗漏了什么?

我有一个函数可以与 Alamofire.request...

一起使用
func getMenuFromIsoShortDate(menuDate: String) {
    let user = Constants.DummyCredentials.UserName
    let password = Constants.DummyCredentials.PassWord

    var urlString = ""
    let dateForWebservice: NSDate? = NSDate.dateFromIsoString(menuDate)

    if let dateForWebservice = dateForWebservice {
        urlString = Constants.WebservicePath.DailyMenu + NSDate.dateToIsoSlash(dateForWebservice)
        println("urlString: \(urlString)")
    }
    let credential = NSURLCredential(user: user, password: password, persistence: .ForSession)

    Alamofire.request(.GET, urlString)
    .authenticate(usingCredential: credential)
    .response {
        (request, response, data, error) in

        if let response = response {
            var statusCode = response.statusCode
            println("-->statusCode: \(statusCode)")
        }

        if (error == nil) {
            var serializationError: NSError?
            let jsonData: AnyObject? = NSJSONSerialization.JSONObjectWithData(data! as! NSData, options: NSJSONReadingOptions.AllowFragments, error: &serializationError)

            var parser: Parser = Parser()
            let menu: Menu = parser.parseMenuJSON(jsonData)

            var dataAccess: DataAccess = DataAccess.sharedInstance
            dataAccess.addMenu(menu)
        } else {
            println("Webservice error: \(error)")
        }
    }
}

但是当我 运行 带有 manager.request 的代码时 - 它 运行s,但给了我一个 -999 错误。这里修改后的代码:

func getMenuFromIsoShortDate(menuDate: String) {
    let user = Constants.DummyCredentials.UserName
    let password = Constants.DummyCredentials.PassWord

    var urlString = ""
    let dateForWebservice: NSDate? = NSDate.dateFromIsoString(menuDate)

    if let dateForWebservice = dateForWebservice {
        urlString = Constants.WebservicePath.DailyMenu + NSDate.dateToIsoSlash(dateForWebservice)
        println("urlString: \(urlString)")
    }
    let credential = NSURLCredential(user: user, password: password, persistence: .ForSession)

    let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
    manager = Alamofire.Manager(configuration: configuration)

    manager.request(.GET, urlString)
    .authenticate(usingCredential: credential)
    .response {
        (request, response, data, error) in

        if let response = response {
            var statusCode = response.statusCode
            println("-->statusCode: \(statusCode)")
        }

        if (error == nil) {
            var serializationError: NSError?
            let jsonData: AnyObject? = NSJSONSerialization.JSONObjectWithData(data! as! NSData, options: NSJSONReadingOptions.AllowFragments, error: &serializationError)

            var parser: Parser = Parser()
            let menu: Menu = parser.parseMenuJSON(jsonData)

            var dataAccess: DataAccess = DataAccess.sharedInstance
            dataAccess.addMenu(menu)
        } else {
            println("Webservice error: \(error)")
        }
    }
}

这里是错误信息:

Webservice error: Optional(Error Domain=NSURLErrorDomain Code=-999 "Abgebrochen" UserInfo=0x7f8f11c3f210 {NSErrorFailingURLKey=http://test.myserver.de:18507/app/services/mampf/get-menu/2015/05/08, NSLocalizedDescription=Abgebrochen, NSErrorFailingURLStringKey=http://test.myserver.de:18507/app/services/mampf/get-menu/2015/05/08})

这有什么问题?

我可以看到两个可能的问题。

问题 1 - 管理器被释放

第一个明显的问题是您是否将自定义 manager 实例保存在内存中。您需要在 属性 中保留管理器,以确保它不会在请求中间被释放。

问题 2 - 缺少默认 HTTP headers

Alamofire.request 和您的 manager.request 之间的唯一区别是您的 manager 缺少 Alamofire 共享管理器默认附加的默认 headers。

public static let sharedInstance: Manager = {
    let configuration: NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()
    configuration.HTTPAdditionalHeaders = Manager.defaultHTTPHeaders

    return Manager(configuration: configuration)
}()

我会将以下行添加到您的管理器初始化中,看看这是否使行为一致。

let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.HTTPAdditionalHeaders = Alamofire.Manager.defaultHTTPHeaders
manager = Alamofire.Manager(configuration: configuration)

希望这能帮助您找到问题的根源。我不清楚为什么缺少默认值 headers 会导致您看到的问题,但如果无法访问您的项目,就很难进一步挖掘。

试试这个

let url:String = "https://domain.com"
var manager : Manager?

override func viewDidLoad() {
    super.viewDidLoad()

    let serverTrustPolicies: [String: ServerTrustPolicy] = [
        "domain.com": .PinCertificates(
            certificates: ServerTrustPolicy.certificatesInBundle(),
            validateCertificateChain: true,
            validateHost: true
        )
    ]


    manager = Manager(
        serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies)
    )
    manager!.request(.GET, url)
        .validate()
        .responseJSON { response in
            if let httpError = response.result.error {
                print(httpError.code)

            }

            else {

                print(response.result.value)
            }

    }


}