我想从教程中将旧代码转换为Swift 3,因为此刻我正在处理的项目已经在Swift 3中。我无法发送POST请求并阅读我收到的JSON。请注意,这些截图是从视频中截取的,因此有可能重复某些代码。 在将json和HTTP“post”代码转换为Swift时出错3
我的代码如下:
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)
我想知道有没有正确地转换大部分代码,以及如何解决这些错误所看到在下面的截图中:
我已经广泛搜查这一点,只有能对大家有点帮助的职位是this post
“?让parseJSON = jsonResult作为NSDictionary的{” 是无效的SWIFT代码,尝试改变,要 “?如果让parseJSON = jsonResult作为NSDictionary的{” – Sealos
@sealos感谢你,当我将其更改为它会给出错误“使用未解析的标识符'jsonResult'” – Riazbapoo
jsonResult声明位于do块内。给我一分钟来写修复。 – Sealos