为什么会出现URL错误?

时间:2015-11-06 17:30:10

标签: swift nsurl foundation itunes-api

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

  

致命错误:在解包可选值时意外发现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()

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

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