2

As it's widely known that an asynchronous post request is better since the user won't get a perception that the app has "crashed" while it's loading the long process.

However, I'm not sure where to start to convert a synchronous post request to an asynchronous post request for a Swift code.


I have this code currently:

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  
                    }

                }
            }
        }
}
glennsl
  • 28,186
  • 12
  • 57
  • 75
Panda
  • 6,955
  • 6
  • 40
  • 55

2 Answers2

3

First of all don't use NSURLConnection as it's deprecated now. Instead use NSURLSession.

You can simply use like this:

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

                } else {
                    print("error=\(error!.localizedDescription)")
                }
            }
        task.resume()
Vishal Sonawane
  • 2,637
  • 2
  • 16
  • 21
  • Thanks for your answer! I'm not sure how do I submit my post values and how do I parse the JSON received? – Panda Feb 22 '17 at 12:32
  • @Panda Your Request will be same also you have done JSON parsing well. Just there may be few changes that you will have to make in order to use in Swift 3. You can easily do that. Just dive into this first. happy Coding..!! – Vishal Sonawane Feb 22 '17 at 12:36
1

You need to really make a lot of changes. Use swift type, instead of NSMutableURLRequest use URLRequest use String instead of NSString instead of NSDictionary & NSArray use Swift Dictionary and 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()
}
Nirav D
  • 71,513
  • 12
  • 161
  • 183