Riazbapoo Riazbapoo - 1 month ago 11
JSON Question

Errors while converting json and HTTP "post" code to Swift 3

I am trying to convert old code from a tutorial to Swift 3 as the project I am working on at the moment is already in Swift 3. I am having trouble sending POST requests and reading the JSON that I receive. Please note that these screenshots are taken from a video so there's a chance that some of the code is repeated. screenshots of the tutorials code

more screenshots

last screenshot

my code is as follows:

let myURL = NSURL(string:"http://localhost/bahApp/scripts/registerUser.php?");
let request = NSMutableURLRequest(url:myURL as! URL)
request.httpMethod = "POST";
let postString = "userEmail=\(userEmail)&userPassword=\(userPassword)&userFirstName=\(userFirstName)&userLastName=\(userLastName)&numberOfConnections=\(numberOfConnections)&installerID=\(installerID)"
request.httpBody = postString.data(using: String.Encoding.utf8);

let task = URLSession.shared.dataTask(with: myURL as URL!) { data, response, error in
DispatchQueue.main.async {
if error != nil{
self.displayAlertMessage(userMessage: (error?.localizedDescription)!)
return
}
do {
if let jsonResult = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:Any]
{print(jsonResult)}

} catch let error as NSError {
print(error.localizedDescription)
}

let parseJSON = jsonResult as? NSDictionary {

var userId = parseJSON["userID"] as? String

if (userId != nil){
var myAlert = UIAlertController(title: "Alert", message: "registration successful", preferredStyle: UIAlertControllerStyle.alert)
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)
myAlert.addAction(okAction);
self.present(myAlert, animated: true, completion: nil)
}else{
let errorMessage = parseJSON["message"] as? String
if (errorMessage != nil){
self.displayAlertMessage(userMessage: errorMessage!)
}
}
}
}
}
task.resume()
}

func displayAlertMessage(userMessage: String){

var myAlert = UIAlertController(title: "Alert", message: userMessage, preferredStyle: UIAlertControllerStyle.alert)
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)
myAlert.addAction(okAction);
self.present(myAlert, animated: true, completion: nil)


I would like to know if i have correctly converted most of the code and how to fix the errors as seen in the screenshot below:

errors

I have searched this extensively and the only post that was able to help a bit was this post

Answer

Your code is trying to use instances which are accessed out of the scope. This is happening because of the declaration inside the do block. Try the following code:

let task = URLSession.shared.dataTask(with: myURL as URL!) { data, response, error in
    DispatchQueue.main.async {
        if let error = error {
            self.displayAlertMessage(userMessage:(error.localizedDescription)!)
            return
        }

        let jsonResult: [String:Any]?
        do {
            jsonResult = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:Any]
            if let result = jsonResult {
                print(result)
            }

        } catch let error as NSError {
            print(error.localizedDescription)
        }

        if let parseJSON = jsonResult as? NSDictionary {

            if let userId = parseJSON["userID"] as? String {
                var myAlert = UIAlertController(title: "Alert", message: "registration successful", preferredStyle: UIAlertControllerStyle.alert)
                let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)
                myAlert.addAction(okAction);
                self.present(myAlert, animated: true, completion: nil)
            } else {
                if let errorMessage = parseJSON["message"] as? String
                    self.displayAlertMessage(userMessage: errorMessage!)
                }
            }
        }
    }
}