如何将同步发布请求转换为异步发布请求?

时间:2017-02-22 12:19:09

标签: ios swift asynchronous synchronous code-conversion

众所周知,异步发布请求更好,因为用户不会感觉到应用已经崩溃了#34;虽然它加载了漫长的过程。

但是,我不知道从哪里开始将同步发布请求转换为Swift代码的异步发布请求。

我目前有这个代码:

func checkLogin () {
    let username:NSString = txtUsername.text! as NSString
    let password:NSString = txtPassword.text! as NSString

        do {
            let post:NSString = "username=\(username)&password=\(password)" as NSString
            NSLog("PostData: %@",post);
            let url:URL = URL(string:"https://example.com/login.php")!
            let postData:Data = post.data(using: String.Encoding.ascii.rawValue)!
            let postLength:NSString = String( postData.count ) as NSString
            let request:NSMutableURLRequest = NSMutableURLRequest(url: url)

            request.httpMethod = "POST"
            request.httpBody = postData
            request.setValue(postLength as String, forHTTPHeaderField: "Content-Length")
            request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
            request.setValue("application/json", forHTTPHeaderField: "Accept")

            var reponseError: NSError?
            var response: URLResponse?
            var urlData: Data?

            do {
                urlData = try NSURLConnection.sendSynchronousRequest(request as URLRequest, returning:&response)
            } catch let error as NSError {
                reponseError = error
                urlData = nil
            }

            if ( urlData != nil ) {
                let res = response as! HTTPURLResponse!;

                NSLog("Response code: %ld", res?.statusCode);

                if ((res?.statusCode)! >= 200 && (res?.statusCode)! < 300) {
                    let responseData:NSString  = NSString(data:urlData!, encoding:String.Encoding.utf8.rawValue)!

                    NSLog("Response ==> %@", responseData);

                    let jsonData:NSDictionary = try JSONSerialization.jsonObject(with: urlData!, options:JSONSerialization.ReadingOptions.mutableContainers ) as! NSDictionary
                    let success:NSInteger = jsonData.value(forKey: "success") as! NSInteger
                    NSLog("Success: %ld", success);

                    if(success == 1)
                    {
                    // do something, code removed
                    } else {
                        var error_msg:NSString

                        if jsonData["error_message"] as? NSString != nil {
                            error_msg = jsonData["error_message"] as! NSString
                        } else {
                            error_msg = "Unknown Error"
                        }
                        // show alert  
                    }

                }
            }
        }
}

2 个答案:

答案 0 :(得分:3)

首先,不要使用NSURLConnection 已弃用。而是使用NSURLSession

您可以这样使用:

let task = URLSession.shared().dataTask(with: request) {
                data, response, error in
                if (data) {

                } else {
                    print("error=\(error!.localizedDescription)")
                }
            }
        task.resume()

答案 1 :(得分:1)

你需要做出很多改变。使用swift类型,而不是NSMutableURLRequest使用URLRequest使用String代替NSString代替NSDictionary&amp; NSArray使用Swift Dictionary和Array

func checkLogin () {
    let username = txtUsername.text!
    let password = txtPassword.text!

    let post = "username=\(username)&password=\(password)"
    NSLog("PostData: %@",post);
    let url:URL = URL(string:"https://example.com/login.php")!
    let postData = post.data(using: .utf8)!
    let postLength = String( postData.count )
    var request = URLRequest(url: url)

    request.httpMethod = "POST"
    request.httpBody = postData
    request.setValue(postLength as String, forHTTPHeaderField: "Content-Length")
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.setValue("application/json", forHTTPHeaderField: "Accept")
    let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
        if error != nil {
            return
        }
        if let jsonData = (try? JSONSerialization.jsonObject(with: data!, options: [])) as? [String:Any] {
            let success = jsonData["success"] as! Int
            if success == 1 {
                //do something,
            }
            else {
                //show alert
            }
        }

    })
    task.resume()
}