2016-03-06 70 views
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 

回答

1

錯誤消息說,這一切,你都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)」);返回},需要更新從我重新啓動服務器時的網址。 –