2017-05-25 41 views
1

我的程序正在使用地圖,並且我有一個UITextField,用戶在其中輸入搜索短語,地圖將在地圖上顯示搜索結果的註釋。 該程序在模擬器中正常工作,但在我的手機上進行測試時,如果輸入兩項作品(如「狗公園」),將會拋出「零,同時展開可選值」錯誤。但是,如果我只輸入「狗」,程序不會將錯誤丟到我的手機上。我在ViewDidLoad中設置了代理,並且所有插座都正確連接。 我在這裏搜索並試圖解決問題無濟於事,所以我想我會問,看看你們是否注意到我錯過了什麼。Swift UIText字段在輸入多個單詞時拋出nil錯誤

下面是該UITextLabel搜索功能:

@IBAction func searchField(_ sender: UITextField) { 
    let allAnnotations = self.mapView.annotations 
    self.mapView.removeAnnotations(allAnnotations) 
    let request = MKLocalSearchRequest() 
    request.naturalLanguageQuery = textField.text! 
    request.region = mapView.region 

    let search = MKLocalSearch(request: request) 
    search.start(completionHandler: {(response, error) in 

     if error != nil{ 
      print("Error occured in search: \(error!.localizedDescription)") 
     }else if response!.mapItems.count == 0{ 
      self.textField.text = "No matches found" 
     }else{ 
      print("Matches found") 
      for item in response!.mapItems{ 
       let annotation = MKPointAnnotation() 
       annotation.coordinate = item.placemark.coordinate 
       annotation.title = item.name 
       annotation.subtitle = item.placemark.thoroughfare! + ", " + item.placemark.locality! + ", " + item.placemark.administrativeArea! 
       self.mapView.addAnnotation(annotation) 
      } 
     } 
    }) 
    sender.resignFirstResponder() 
} 
+1

在哪一行發生錯誤?你應該考慮使用'guard let'或'let let'來解開你的選項,而不是用'!'強制解包。這可以幫助你瞭解事情發生錯誤的地方。 –

+0

試過了,它仍然拋出了錯誤。遍歷調試器中的代碼,並在「self.mapView.addAnnotation」行後面引發錯誤。有什麼奇怪的是,如果你輸入一個單詞很好,但是兩個,它會引發錯誤。更不用說它在模擬器中完美了。 – oblagon

+1

你在哪一行出錯? –

回答

0

尋找到這之後所以我越發現,不需要增加了naturalLanguageQuery串的答案。問題是for循環返回一個空值。讓警衛讓迴應解決了它。

@IBAction func searchField(_ sender: UITextField) { 
    let allAnnotations = self.mapView.annotations 
    self.mapView.removeAnnotations(allAnnotations) 
    let request = MKLocalSearchRequest() 
    request.naturalLanguageQuery = textField.text! 
    request.region = mapView.region 

    let search = MKLocalSearch(request: request) 
    search.start(completionHandler: {(response, error) in 

     if error != nil{ 
      print("Error occured in search: \(error!.localizedDescription)") 
     }else if response!.mapItems.count == 0{ 
      self.textField.text = "No matches found" 
     }else{ 
      print("Matches found") 
      guard let response = response?.mapItems else { return } 
      for item in response{ 
       let annotation = MKPointAnnotation() 
       annotation.coordinate = item.placemark.coordinate 
       annotation.title = item.name 
       annotation.subtitle = item.placemark.thoroughfare! + ", " + item.placemark.locality! + ", " + item.placemark.administrativeArea! 

       self.mapView.addAnnotation(annotation) 
      } 
     } 
    }) 
    sender.resignFirstResponder() 
} 
相關問題