1

我正在使用 iTunes 搜索 API,为了进行测试,我正在搜索“愤怒的小鸟”并打印结果。但是当我将其转换urlPath为 NSURL 时,我得到了一个nil值。我该如何解决?有urlPath链接,但它nil在 url 变量中。这是确切的错误:

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

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()
4

2 回答 2

1

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

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

于 2015-11-06T17:44:41.353 回答
0

当 URL 包含空格等非法字符时,NSURL 返回 nil。验证您的 URlString 是否正确。

于 2015-11-06T17:37:40.540 回答