2015-11-06 84 views
1

我正在使用iTunes搜索API,並且爲了測試,我正在搜索「憤怒的小鳥」並打印結果。但是當我將urlPath轉換成NSURL時,我得到了一個nil值。我該如何解決? urlPath有鏈接,但在url變量中是nil。這是確切的錯誤:爲什麼會發生URL錯誤?

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() 
+0

通過在瀏覽器中粘貼url來檢查是否正在那裏工作 –

回答

1

stringByAddingPercentEscapesUsingEncoding返回一個可選的字符串,那麼你得到的其實是這樣的:

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

的解決方案是安全解開可選:

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

0

NSURL返回nil當URL包含非法字符,如空間。驗證你的URlString是否正確。

相關問題