如何在Swift中调用异步任务?

时间:2018-10-21 15:59:59

标签: ios swift xcode

我是Swift的新手,因此我想尝试将http调用包装到一个函数中以供重用,但是由于它需要一个完成块,因此我不确定如何调用它。这是我的代码,

func httpPost(_ path: String, _ parameters: [String: Any], completion:@escaping(_ ret:Any?,_ err:Error?) -> Void){

        let headers = [
            "Content-Type": "application/json",
            "cache-control": "no-cache"
        ]

        let postData = try? JSONSerialization.data(withJSONObject: parameters, options: [])

        var request = URLRequest(url: URL(string: path)! as URL,
                                 cachePolicy: .useProtocolCachePolicy,
                                 timeoutInterval: 10.0)
        request.httpMethod = "POST"
        request.allHTTPHeaderFields = headers
        request.httpBody = postData

        let session = URLSession.shared
        let dataTask = session.dataTask(with: request) { (data, response, error) -> Void in
            guard let data = data else {
                completion(nil,error)
                return
            }
            do{
                try self.validate(response)
                let json = try JSONSerialization.jsonObject(with: data, options: [])
                completion(json,nil)

            }catch{
                print(error)
                completion(nil,error)
            }

        }

        dataTask.resume()
    }

我的问题是如何调用此函数?

1 个答案:

答案 0 :(得分:1)

我认为Xcode本身会建议如何实现调用此方法。如果您尝试键入“ httpPo ...”,则应该看到自动完成列表:

enter image description here

双击它:

enter image description here

我认为pathparameters很容易理解,它可能与completion闭包有关;您可以做的就是双击它,因此:

enter image description here

差不多就可以了!您现在要做的就是填写:

httpPost("your path", [: ]) { (response, error) in
    // ...
}