我想從教程中將舊代碼轉換爲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