2016-11-04 58 views
-1

我想從教程中將舊代碼轉換爲Swift 3,因爲此刻我正在處理的項目已經在Swift 3中。我無法發送POST請求並閱讀我收到的JSON。請注意,這些截圖是從視頻中截取的,因此有可能重複某些代碼。 screenshots of the tutorials code在將json和HTTP「post」代碼轉換爲Swift時出錯3

more screenshots

last screenshot

我的代碼如下:

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) 

我想知道有沒有正確地轉換大部分代碼,以及如何解決這些錯誤所看到在下面的截圖中:

errors

我已經廣泛搜查這一點,只有能對大家有點幫助的職位是this post

+0

「?讓parseJSON = jsonResult作爲NSDictionary的{」 是無效的SWIFT代碼,嘗試改變,要 「?如果讓parseJSON = jsonResult作爲NSDictionary的{」 – Sealos

+0

@sealos感謝你,當我將其更改爲它會給出錯誤「使用未解析的標識符'jsonResult'」 – Riazbapoo

+0

jsonResult聲明位於do塊內。給我一分鐘來寫修復。 – Sealos

回答

2

你的代碼試圖使用被訪問的範例以外的實例。這是因爲do塊內的聲明而發生的。試試下面的代碼:

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!) 
       } 
      } 
     } 
    } 
} 
+0

我愛你這個(沒有同性戀),非常感謝 – Riazbapoo

2

你忘了let parseJSON之前添加if

if let parseJSON = jsonResult as? NSDictionary { 
    //... 
} 
+0

我按照你所說的,當我改變它,它給出了錯誤「使用未解析的標識符'jsonResult'」 – Riazbapoo

+0

你應該將這段代碼移動到包含'if let jsonResult = try JSONSerialization.jsonObject(with :data !, options:.allowFragments)as? [字符串:任何] {print(jsonResult)}' – njuri

+0

幫助了很多謝謝,我升職了,但因爲im低於15代表它沒有顯示 – Riazbapoo

相關問題