gpt4 book ai didi

swift - 注册/登录 swift 2.0 错误

转载 作者:行者123 更新时间:2023-11-30 10:06:12 25 4
gpt4 key购买 nike

不太确定我在这里缺少什么来使该代码正常工作。尝试制作一个带有登录/注册连接到服务器的应用程序,但我似乎无法让它工作。这是我的代码:

    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

最佳答案

错误消息说明了一切,您正在取消引用一个 nil data 值,可能是 JSONObjectWithData(data!, ...行中的 data code>,但从调试器停止的位置应该是显而易见的。防止错误,然后从那里向上游走。

if error != nil { handle error and abort }

... etc

关于swift - 注册/登录 swift 2.0 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35833031/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com