为什么发帖请求在第二次通话时工作得更快?

时间:2017-05-18 14:45:59

标签: swift post nsurlrequest nsjsonserialization

我启动了该应用。按下调用此功能的按钮,等待2-3秒,然后获取JSON。然后我再次按下它,等待0-1然后我得到JSON。你能解释一下它发生的原因吗?我怎么能避免它?

public func serverUserRegister(userPhone: String?, userEmail: String?, completionHandler: @escaping ((String) -> ())) {

    if let phone = userPhone {
        if let email = userEmail {

            let url = URL(string: "https://example.com/service.php")!
            let session = URLSession.shared
            let request = NSMutableURLRequest(url: url)
            request.httpMethod = "POST"
            request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
            let paramString = "phone=\(phone)&email=\(email)"
            request.httpBody = paramString.data(using: .utf8)

            let task = session.dataTask(with: request as URLRequest) { (data, response, error) in
                guard let _: Data = data, let _: URLResponse = response, error == nil else {
                    return
                }
                if let json = try? JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary {
                    if let jsonStatus = json?["status"] as? String {
                        completionHandler(jsonStatus)
                    }
                }
            }

            task.resume()

        }
    }
}

0 个答案:

没有答案