2016-06-30 13 views
1

私は、CoreLocationとMapKitのfrimeworksベースのアプリケーションでローカル検索を実装しています。私はこのTutorialSwiftの関数エラー処理

次私は、エラーの下にエラーを取得していています:ここで

Cannot convert value of type '(MKLocalSearchResponse!, NSError!) -> ()' to expected argument type 'MKLocalSearchCompletionHandler' (aka '(Optional, Optional) ->()')

は私のコードです:

import UIKit 
import CoreLocation 
import MapKit 


class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate{ 
    private let LocationManager = CLLocationManager() 
    let request = MKLocalSearchRequest() 
    private var previousPoint:CLLocation? 
    private var totalMovementDistance:CLLocationDistance = 0 




    @IBOutlet var mapView: MKMapView! 


    @IBOutlet var searchText: UITextField! 
    var matchingItems: [MKMapItem] = [MKMapItem]() 

    @IBAction func textFieldReturn(sender:AnyObject) { 
     sender.resignFirstResponder() 
     mapView.removeAnnotations(mapView.annotations) 
     self.performSearch() 

    } 

    @IBOutlet var latitudeLabel: UILabel! 
    @IBOutlet var longitudeLabel: UILabel! 
    @IBOutlet var horizontalAccuracy: UILabel! 
    @IBOutlet var altitudeLabel: UILabel! 
    @IBOutlet var verticalAccuracyLabel: UILabel! 
    @IBOutlet var distanceTraveledLabel: UILabel! 






    override func viewDidLoad() { 
     super.viewDidLoad() 
     LocationManager.delegate = self 
     LocationManager.desiredAccuracy = kCLLocationAccuracyBest 
     LocationManager.requestWhenInUseAuthorization() 



     // Do any additional setup after loading the view, typically from a nib. 
    } 



    func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) { 
     print("Authorization Status Changed to \(status.rawValue)") 
     switch status { 
     case .Authorized, .AuthorizedWhenInUse: 
      LocationManager.startUpdatingLocation() 
      mapView.showsUserLocation = true 

     default: 
      LocationManager.stopUpdatingLocation() 
      mapView.showsUserLocation = false 
     } 
    } 

    func locationManager(manager: CLLocationManager, didFailWithError error: NSError) { 
     let errorType = error.code == CLError.Denied.rawValue ? "Access Denied": "Error \(error.code)" 
     let alertController = UIAlertController(title: "Location Manager Error", message: errorType, preferredStyle: .Alert) 
     let okAction = UIAlertAction(title: "OK", style: .Cancel, handler: {action in}) 
     alertController.addAction(okAction) 
     presentViewController(alertController, animated: true, completion: nil) 
    } 

    func performSearch() { 

     matchingItems.removeAll() 
     let request = MKLocalSearchRequest() 
     request.naturalLanguageQuery = searchText.text 
     request.region = mapView.region 

     let search = MKLocalSearch(request: request) 

     search.startWithCompletionHandler { (localResponse:MKLocalSearchResponse?, error: NSError?) -> Void in 


      if error != nil { 
       print("Error occured in search: \(error?.localizedDescription)") 
      } else if localResponse == 0 { 
       print("No matches found") 
      } else { 
       print("Matches found") 

       for item in localResponse.mapItems { 
        print("Name = \(item.name)") 
        print("Phone = \(item.phoneNumber)") 

        self.matchingItems.append(item as MKMapItem) 
        print("Matching items = \(self.matchingItems.count)") 

        var annotation = MKPointAnnotation() 
        annotation.coordinate = item.placemark.coordinate 
        annotation.title = item.name 
        self.mapView.addAnnotation(annotation) 
       } 
      } 
     } 
    } 


    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 
     let newLocation = (locations as [CLLocation]) [locations.count - 1] 

     let latitudeString = String(format: "%g\u{00B0}", newLocation.coordinate.latitude) 
     latitudeLabel.text = latitudeString 

     let longitudeString = String(format: "%g\u{00B0}", newLocation.coordinate.longitude) 
     longitudeLabel.text = longitudeString 

     let horizontalAccuracyString = String(format: "%gm", newLocation.horizontalAccuracy) 
     horizontalAccuracy.text = horizontalAccuracyString 

     let altitudeString = String(format: "%gm", newLocation.altitude) 
     altitudeLabel.text = altitudeString 

     let verticalAccuracyString = String(format: "%gm", newLocation.verticalAccuracy) 
     verticalAccuracyLabel.text = verticalAccuracyString 

     if newLocation.horizontalAccuracy < 0 { 
      //invalid accuracy 
      return 

     } 


     if newLocation.horizontalAccuracy > 100 || 
      newLocation.verticalAccuracy > 50 { 
       return 
     } 

     if previousPoint == nil { 
      totalMovementDistance = 0 
      let start = Place(title:"Strating Point", subtitle:"This is where we started", coordinate:newLocation.coordinate) 
      mapView.addAnnotation(start) 
      let region = MKCoordinateRegionMakeWithDistance(newLocation.coordinate, 100, 100) 
      mapView.setRegion(region, animated:true) 


     }else { 
      print("movement distance: \(newLocation.distanceFromLocation(previousPoint!))") 
      totalMovementDistance += newLocation.distanceFromLocation(previousPoint!) 

     } 

     previousPoint = newLocation 

     let distanceString = String(format: "%gm", totalMovementDistance) 
     distanceTraveledLabel.text = distanceString 



    } 



} 

エラーがこの行にある:

編集
search.startWithCompletionHandler({(response: 
      MKLocalSearchResponse!, 

enter image description here

+0

あなたが受け取っているエラーは、この変数がオプションのため、アクセスするために必要なものですか?何かを使用する必要があります: 'error?.localizedDescription'または最初に' let let error = error { //あなたのコード} ' –

答えて

2

!議論の中で? 例(すなわち、メソッドの署名だから):

search.startWithCompletionHandler { (localResponse:MKLocalSearchResponse?, error:NSError?) -> Void in 

    } 
+0

ありがとうございました。それはエラーを削除するのに役立ちました。 –

1

エラーメッセージは、単にそれが任意のタイプを受け取るための方法の署名は、間違っていると言います。

⇧⌘0を押すとMKLocalSearchCompletionHandlerを入力して、それを確認して、あなたは

typealias MKLocalSearchCompletionHandler = (MKLocalSearchResponse?, NSError?) -> Void

だから、それは

search.startWithCompletionHandler({(response: 
     MKLocalSearchResponse?, 
     error: NSError?) in ... 

だがすることができます表示されます - とすべきである - 型注釈に

を省略します
search.startWithCompletionHandler({(response, error) in ... 
+0

ありがとう、私はあなたが提案したように私のコードを更新しました今、私はそれを克服する方法を得ていない3つのエラーが表示されます。申し訳ありません、私はこれで完全な初心者です。 –

+0

'localResponse'は' response'と同じではありません。パラメータ名の一貫性を確認 – vadian

+0

ViewControllerのコード全体を追加しました –

1

次のとおりです。

func performSearch() { 

    var matchingItems = [MKMapItem]() 
    let mapView = MKMapView(frame: CGRectMake(0,0,300,300)) 

    let request = MKLocalSearchRequest() 
    request.naturalLanguageQuery = "Restaurants 30518" 
    request.region = mapView.region 

    let search = MKLocalSearch(request: request) 

    search.startWithCompletionHandler { (response, error) in 

     if let error = error { 
      print("Error occured in search: \(error.localizedDescription)") 
     } else if let response = response { 
      print("Got response") 
      if response.mapItems.count == 0 { 
       print("No matches found") 
      } else { 
       print("Matches found") 

       for item in response.mapItems as [MKMapItem] { 
        print("Name = \(item.name)") 
        print("Phone = \(item.phoneNumber)") 

        matchingItems.append(item as MKMapItem) 
        print("Matching items = \(matchingItems.count)") 

        let annotation = MKPointAnnotation() 
        annotation.coordinate = item.placemark.coordinate 
        annotation.title = item.name 
        mapView.addAnnotation(annotation) 
       } 
      } 
     } 
    } 
} 

応答とエラーはオプションです。強制的にアンラップしないでください。

+0

この場合、強制アンラッピングは問題ありません。エラーが発生した場合、 'error'は間違いなく' nil'であり、エラーがなければ、 'response'は' nil'ではありません。 – vadian

+0

@vadian私はメソッドのシグネチャを意味しました。 (レスポンス:MKLocalSearchResponse !,エラー:NSError!)が間違っています。メソッドシグネチャのオプションとしてそれらを残し、それらをアンラップする必要があります。 –

関連する問題