-1

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

Community
  • 1
  • 1
Riazbapoo
  • 61
  • 5
  • "let parseJSON = jsonResult as? NSDictionary {" is not valid Swift code, try changing that to "if let parseJSON = jsonResult as? NSDictionary {" – Sealos Nov 04 '16 at 09:29
  • @sealos thank you, when i change it to that it gives the error "use of unresolved identifier 'jsonResult'" – Riazbapoo Nov 04 '16 at 09:36
  • The jsonResult declaration is inside a do block. Give me a minute to write the fix. – Sealos Nov 04 '16 at 09:39

2 Answers2

2

You forgot to add if before let parseJSON.

if let parseJSON = jsonResult as? NSDictionary {
  //...
}
Juri Noga
  • 4,363
  • 7
  • 38
  • 51
  • i had it as you said, when i change it to that it gives the error "use of unresolved identifier 'jsonResult'" – Riazbapoo Nov 04 '16 at 09:35
  • You should move this block of code below the line containing `if let jsonResult = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:Any] {print(jsonResult)}` – Juri Noga Nov 04 '16 at 09:39
  • that helped a lot thank you, i upvooted but because im below 15 rep it doesnt show – Riazbapoo Nov 04 '16 at 09:52
2

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!)
                }
            }
        }
    }
}
Sealos
  • 562
  • 3
  • 15