使用URL会话命中api时请求超时

时间:2018-06-05 09:44:42

标签: ios swift urlsession

我已经创建了一个用于命中API方法的函数,我将它用于整个项目。这个功能工作得很完美,但是现在当我使用这个功能时,请求时间最多,请求时间更长,我的请求超时(仅当我连接到wifi时)。我不确定它是后端问题还是我的代码。

// MARK: Calling Web services
class func callWebServices(url: String, methodName: String, parameters: String, showLoader: Bool, completion: @escaping CompletionHandler) {

    var url_param = url
    if showLoader {
        KVNProgress.show()
    }
    if(methodName == "GET" && parameters != "") {
        url_param = url_param + "?" + parameters
    }
    var request = URLRequest(url: URL(string: url_param)!)
    request.httpMethod = methodName

    if(methodName == "POST" && parameters != "") {
        let postString = parameters
        request.httpBody = postString.data(using: .utf8)
    }
    let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
        guard let data = data, error == nil else {
            print("error = \(String(describing: error))")
            return
        }
        if let httpsStatus = response as? HTTPURLResponse, httpsStatus.statusCode != 200 {
            print("Status Code should be 200, but it is \(httpsStatus.statusCode)")
            print("response = \(String(describing: response))")
        }
        do {
            let dictData = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! NSDictionary

            DispatchQueue.main.async {
                print("Json Result :\(dictData)")
                KVNProgress.dismiss()
                completion(dictData)
            }
        } catch {
            KVNProgress.dismiss()
            print("error is : \(error)")
        }
    }
    task.resume()
}

0 个答案:

没有答案