gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 05:41:48 25 4
gpt4 key购买 nike

我正在尝试使用 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 变量时,我不断收到这个错误:

fatal error: unexpectedly found nil while unwrapping an Optional value

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

越来越奇怪了..下面

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

输出

http://localhost:9142/account/validate fatal error: unexpectedly found nil while unwrapping an Optional value

我真的不明白错误是从哪里来的,因为我是 Swift 的新手

最佳答案

发生的事情是您被迫展开设置为 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

关于php - Xcode- swift -NSURL : "fatal error: unexpectedly found nil while unwrapping an Optional value",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28765260/

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