Xcode-Swift-NSURL:“;致命错误:在展开可选值“”时意外发现nil;


Xcode - Swift - NSURL : "fatal error: unexpectedly found nil while unwrapping an Optional value"

我正在尝试使用PHP API和Swift客户端在Xcode Playground中测试OAuth2实现。基本上,我的代码看起来像这个

let url = NSURL(string: "http://localhost:9142/account/validate")!
var request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.HTTPBody!.setValue("password", forKey: "grant_type")
// Other values set to the HTTPBody
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response, data, error) in
    // Handle response here
}

但是当我实例化url变量时,我一直收到这个错误

致命错误:在展开可选值时意外发现nil

当我实例化它时,我试着不打开它,而是当我使用它时,它没有改变任何东西,错误出现在我第一次打开它的时候。

它变得越来越奇怪。。以下

let url = NSURL(string: "http://localhost:9142/account/validate")!
println(url)

输出

http://localhost:9142/account/validate致命错误:在展开可选值时意外发现nil

我真的不明白错误是从哪里来的,因为我对Swift 真的很陌生

发生的情况是,您被迫展开设置为零的HTTPBody,导致以下行出现运行时错误:

request.HTTPBody!.setValue("password", forKey: "grant_type")

您需要为请求主体创建一个NSData对象,然后将其分配给请求。HTTPBody符合以下代码:

let url = NSURL(string: "http://localhost:9142/account/validate")!
var request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
// Create a parameter dictionary and assign to HTTPBody as NSData
let params = ["grant_type": "password"]
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions.allZeros, error: nil)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response, data, error) in
    // Handle response here
}

我希望这能帮助解决你的问题。

更新:

为了在不使用JSON序列化程序的情况下序列化数据,您可以创建自己的类似程序:

func dataWithParameterDictionary(dict: Dictionary<String, String>) -> NSData? {
    var paramString = String()
    for (key, value) in dict {
        paramString += "'(key)='(value)";
    }
    return paramString.dataUsingEncoding(NSASCIIStringEncoding, allowLossyConversion: false)
} 

并这样称呼它:

let dict = ["grant_type": "password"]
let data = dataWithParameterDictionary(dict)
request.HTTPBody = data