2016-11-21 43 views
0

我我的代碼更新到斯威夫特3和大部分轉換了罰款,除了從URLSession和我不能找到一個解決這個錯誤:更新的URLSession到SWIFT 3投擲的錯誤

Cannot invoke 'dataTask' with an argument list of type '(with: NSMutableURLRequest, completionHandler: (Data?, URLResponse?, NSError?) -> Void)'

這是我的代碼:

let post:NSString = "username=\(username)&userPassword=\(password)&userEmail=\(email)" as NSString 

    let url:URL = URL(string: "http://ec2-54-201-55-114.us-west-2.compute.amazonaws.com/wickizerApp/ApplicationDB/scripts/registerUser.php")! 

    let request = NSMutableURLRequest(url: url) 
    request.httpMethod = "POST" 
    request.httpBody = post.data(using: String.Encoding.utf8.rawValue) 


    URLSession.shared.dataTask(with: request, completionHandler: { (data:Data?, response:URLResponse?, error:NSError?) -> Void in 

     DispatchQueue.main.async 
      { 

       if error != nil { 
        self.displayAlertMessage(error!.localizedDescription) 
        return 
       } 

       do { 
        let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary 

        if let parseJSON = json { 

         let status = parseJSON["status"] as? String 

         if(status! == "200") 
         { 
          let myAlert = UIAlertController(title: "Alert", message: "Registration successful", preferredStyle: UIAlertControllerStyle.alert); 

          let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default){(action) in 

           self.dismiss(animated: true, completion: nil) 
          } 

          myAlert.addAction(okAction); 
          self.present(myAlert, animated: true, completion: nil) 
         } else { 
          let errorMessage = parseJSON["message"] as? String 
          if(errorMessage != nil) 
          { 
           self.displayAlertMessage(errorMessage!) 
          } 

         } 

        } 
       } catch{ 
        print(error) 
       } 



     } 

    }).resume() 

在swift 3中有沒有不同的方式來處理請求,或者他們是否改變了做這些請求的方式?

+0

可能的複製[轉換雨燕2.3雨燕3.0 - 錯誤,不能使用類型']的參數列表調用'dataTask'(http://stackoverflow.com/questi附件/ 40451699 /轉換-迅速-2-3到SWIFT-3-0-錯誤不能-調用-datatask與 - 一個-申辯) – vadian

回答

2

編譯器要URLRequestError

var request = URLRequest(url: url) 
request.httpMethod = "POST" 
request.httpBody = post.data(using: .utf8) 

URLSession.shared.dataTask(with: request, completionHandler: { (data:Data?, response:URLResponse?, error:Error?) -> Void in 

}) 

或者更短

URLSession.shared.dataTask(with: request, completionHandler: { (data, response, error) in 

}) 

或者更短

URLSession.shared.dataTask(with: request) { (data, response, error) in 

}