请帮忙,我对Swift很新。如果我执行一次,搜索栏中的API调用工作正常。但是,当我清除搜索栏并再试一次时,我收到此错误:
fatal error: unexpectedly found nil while unwrapping an Optional value
在这一行:
mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: URLString.URLString)!)
这是我的代码。请帮忙:
// Functions for adding search
func createSearchBar() {
searchBar.placeholder = "Anchor Steam"
searchBar.delegate = self
// put into navigation bar
self.navigationItem.titleView = searchBar
}
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
searchBar.resignFirstResponder()
makeAPICall(searchBar.text!)
}
func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
self.searchBar.showsCancelButton = true
}
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
searchBar.showsCancelButton = false
searchBar.text = ""
searchBar.resignFirstResponder()
self.searchResultTableView.reloadData()
}
func makeAPICall(beer: String) {
print("THE SEARCHED BEER IS \(beer)")
Alamofire.request(.GET, "https://api.untappd.com/v4/search/beer?q=\(beer)&client_id=AAA&client_secret=AAA").responseJSON { response in
if let json = response.result.value {
print ("Connection to API successful!")
if let secondJSON = json["response"] as! NSDictionary? {
if let beersJSON = secondJSON["beers"] as! NSDictionary? {
if let beerItems = beersJSON["items"] as! [NSDictionary]? {
var beersJsonArray: [NSDictionary] = []
for beerObject in beerItems {
let insideBeerHash = beerObject["beer"]
beersJsonArray.append(insideBeerHash as! NSDictionary)
}
self.beers = Beer.convertBeers((beersJsonArray as? [NSDictionary]!)!)
self.searchResultTableView.reloadData()
}
}
}
}
}
}
答案 0 :(得分:0)
选项:
1)确保 URLString.URLString 已定义
2)如果尝试使用:let url:
let mutableURLRequest = NSMutableURLRequest(string:URLString.URLString)!
3)或者也许:
let mutableURLRequest = NSURL(string:URLString.URLString)!