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

标签 php xcode swift nsurl null

我正在尝试使用 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/

相关文章:

php - 如何在if else语句中调出mysql的结果

xcode - 如何以编程方式将功能键设置为等效键

ios - 并发调度队列在 Xcode 4 Debug Navigator 中显示为串行

Xcode 11 添加新的约束设置为零 : use set value instead of default/standard

objective-c - 为什么 Xcode 的调试器在使用 Swift 时会这样跳来跳去?

swift - 如何从 View Controller 中触发异步请求

php - 如何使用 GuzzleHttp 重写此代码

javascript - 如果某些 cookie 是通过 javascript 创建的,我如何使用 PHP 检查?

ios - TableView 行数函数未正确返回数组项计数?

javascript - 如何将 PHP 变量传递给 Javascript 函数