在swift 2.0中注册/登录错误

问题描述:

不太确定我在这里失踪的代码是否工作。尝试使登录/注册连接到服务器的应用程序,但我似乎无法让它工作。这是我的代码:在swift 2.0中注册/登录错误

do { 

     let post:NSString = "username=\(username)&password=\(password)" 

     NSLog("PostData: %@",post) 

     let url:NSURL = NSURL(string: "http://www.ec2-54-191-63-219.us-west-2.compute.amazonaws.com/userRegistration.php")! 

     let postData:NSData = post.dataUsingEncoding(NSUTF8StringEncoding)! 

     let request:NSMutableURLRequest = NSMutableURLRequest(URL: url) 
     request.HTTPMethod = "POST" 
     request.HTTPBody = postData 

     let task = NSURLSession.sharedSession().dataTaskWithRequest(request) 
      {data, response, error in 

       do { 
        let json = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers) as? NSDictionary 

        if let parsejson = json 
        { 
         let resultValue:String = parsejson["status"] as! String 

         print("result: \(resultValue)") 


         if (resultValue == "Success") 
         { 
          let alert = UIAlertController(title: "Success", message: "Registration Successful", preferredStyle: UIAlertControllerStyle.Alert) 

          let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default){action in self.dismissViewControllerAnimated(true, completion: nil)} 

          alert.addAction(okAction) 

          self.presentViewController(alert, animated: true, completion: nil) 
         } 
         else 
         { 
         print(resultValue) 
         } 
        } 


       } catch { 
        print("failed: \(error)") 
       } 
     } 

     task.resume() 

这是错误我得到当我尝试添加帐户:

PostData: username=Optional("josh")&password=Optional("test") 
fatal error: unexpectedly found nil while unwrapping an Optional value 

错误消息说,这一切,你都derefencing一个零data价值,可能data在线JSONObjectWithData(data!, ...,但它应该从调试器停止的位置明显。警惕错误,并从此上游。

if error != nil { handle error and abort } 

... etc 
+0

thx used guard error == nil && data!= nil else {print(“error = \(error)”);返回},需要更新从我重新启动服务器时的网址。 –