Alamofire:完成错误-代码:-1001

时间:2018-07-31 07:22:59

标签: ios swift xcode request alamofire

这样的代码:

import Foundation
import Alamofire
struct Request {
var alamoFireManager : SessionManager?
init() {
    let configuration = URLSessionConfiguration.default
            configuration.timeoutIntervalForRequest = 20
    configuration.requestCachePolicy = .useProtocolCachePolicy
            alamoFireManager = Alamofire.SessionManager(configuration: configuration)
}

func sendRequest() {

    alamoFireManager?.request(url,method: method, parameters: body, encoding: JSONEncoding.default,headers: headers).responseJSON { response in

    }
}
}

3 个答案:

答案 0 :(得分:2)

我已经做到了,并且可以正常工作(swift 4代码)。

import UIKit
import Alamofire

class SplashViewController: UIViewController {

    var alamoFireManager = Alamofire.SessionManager.default

    override func viewDidLoad() {
        super.viewDidLoad()

        self.callPostApi()

    }

    func callPostApi() {

        let configuration = URLSessionConfiguration.default
        configuration.timeoutIntervalForRequest = 20 // seconds
        configuration.timeoutIntervalForResource = 20
        configuration.requestCachePolicy = .useProtocolCachePolicy
        alamoFireManager = Alamofire.SessionManager(configuration: configuration)

        alamoFireManager.request(url, method: .post, parameters: ["jsondata":base64EncodedString])
            .responseJSON { response in

                switch (response.result) {
                case .success:

                    print(response.data as? Data)

                    if let json = response.result.value {
                        print("JSON: \(json)") // Here is your JSON Response
                    }
                    //do json stuff

                case .failure(let error):

                    if error._code == NSURLErrorTimedOut || error._code == -1005{
                        //HANDLE TIMEOUT HERE
                        print("TimeOut")
                    }
                    print("\n\nAuth request failed with error:\n \(error)")
                    break
               }
        }

    }

}

答案 1 :(得分:0)

SessionManager 不适用于我。最好在 Alamofire 中使用这样的代码:

let request = URLRequest(url: url)
request.httpMethod = "GET"
//Some configuration


Alamofire.request(request).responseJSON {
                response in

}

答案 2 :(得分:0)

这是超时错误。如果可能,只需增加超时值,或提高API的性能。