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.
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:
I have searched this extensively and the only post that was able to help a bit was this post