2017-02-22 95 views
2

衆所周知,異步發佈請求更好,因爲用戶不會在加載漫長過程時感覺應用「崩潰」。如何將同步發佈請求轉換爲異步發佈請求?

但是,我不確定從哪裏開始將同步發佈請求轉換爲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 
        } 

       } 
      } 
     } 
} 

回答

1

你需要真正做出了很大的變化。使用SWIFT類型,而不是NSMutableURLRequest使用URLRequest使用String代替NSString代替NSDictionary & NSArray使用SWIFT字典和數組

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() 
} 
3

先不使用NSURLConnection,因爲它是過時現在。請使用NSURLSession

您可以簡單地使用這樣的:

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

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

謝謝您的回答!我不確定如何提交我的帖子值,以及如何解析收到的JSON? – Panda

+0

@Panda你的請求也會一樣,你也完成了JSON解析。爲了在Swift 3中使用,您可能需要做的改變可能很少。您可以輕鬆地做到這一點。首先深入這一點。快樂編碼..! –