我正在尝试使用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的新手
答案 0 :(得分:0)
正在发生的事情是你被迫展开设置为nil的HTTPBody,导致此行出现运行时错误:
request.HTTPBody!.setValue("password", forKey: "grant_type")
您需要为请求正文创建一个NSData对象,然后根据以下代码将其分配给request.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