为什么会出现 URL 错误?

Why is the URL error occurring?

我正在使用 iTunes 搜索 API,为了测试,我正在搜索 "Angry Birds" 并打印结果。但是当我将 urlPath 转换为 NSURL 时,我得到了一个 nil 值。我该如何解决? urlPath 有 link,但它在 url 变量中是 nil。这是确切的错误:

fatal error: unexpectedly found nil while unwrapping an Optional value.

var searchTerm: String = "Angry Birds"
var itunesSearchTerm = searchTerm.stringByReplacingOccurrencesOfString(" ", withString: "+", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil)
var escapedSearchTerm = itunesSearchTerm.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
var urlPath = "https://itunes.apple.com/search?term=\(escapedSearchTerm)&media=software"
var url: NSURL = NSURL(string: urlPath)!
var request: NSURLRequest = NSURLRequest(URL: url)
var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)!

print("Search iTunes API at URL \(url)")

connection.start()

NSURL returns nil 当 URL 包含非法字符如 space 时。验证您的 URlString 是否正确。

stringByAddingPercentEscapesUsingEncoding returns 一个可选的字符串,所以你得到的实际上是这样的:

https://itunes.apple.com/search?term=Optional("Angry+Birds")&media=software

解决方案是安全地解包 Optional:

if let escapedSearchTerm = itunesSearchTerm.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) {
    let urlPath = "https://itunes.apple.com/search?term=\(escapedSearchTerm)&media=software"
    let url = NSURL(string: urlPath)
    // ...
}

结果:

https://itunes.apple.com/search?term=Angry+Birds&media=software