无法识别的选择器,即使选择器已正确命名

时间:2017-03-07 19:40:38

标签: ios swift mapbox nsnotificationcenter unrecognized-selector

我正在使用MapBoxNavigation.swift来构建将用户导航到某个位置的应用。直到导航开始,一切正常。但是当导航开始并且MapBoxNavigation.swift发布帖子NSNotification时(请参阅有关库如何工作的文档),我写的Observer会抛出此错误消息:

app[49184:2686603] -[__NSCFConstantString navProgressDidChange:]: unrecognized selector sent to instance 0x1096dfdb0

这是从MapBoxNavigation.swift发布通知的代码:

NotificationCenter.default.post(name: RouteControllerAlertLevelDidChange, object: self, userInfo: [
        RouteControllerAlertLevelDidChangeNotificationRouteProgressKey: routeProgress,
        RouteControllerAlertLevelDidChangeNotificationDistanceToEndOfManeuverKey: userDistance,
        RouteControllerProgressDidChangeNotificationIsFirstAlertForStepKey: isFirstAlertForStep
        ])

这应该是所有必要的代码:

import Foundation
import UIKit
import Mapbox
import MapboxDirections
import MapboxNavigation
import CoreLocation
import Alamofire
import SWXMLHash
import DateTimePicker

//Primary ViewController, used for basically everything
class ViewController: UIViewController, MGLMapViewDelegate, CLLocationManagerDelegate, UITextFieldDelegate, UIGestureRecognizerDelegate {

    lazy var geocoder = CLGeocoder()
    @IBOutlet weak var addressTextField: SearchTextField! //SearchTextField
    @IBOutlet var mapView: MGLMapView! //MapView of MapBox    

    @IBOutlet weak var BookingUIView: UIView!
    @IBOutlet weak var BookingView: UIView!

    //Used to geocode the Addresses
    let locationManager = CLLocationManager()
    var searched = false
    var keyboardEnabled = false
    var navigationStarted = false


    //Getting the route object
    let directions = Directions.shared
    let waitForInterval: TimeInterval = 5

    @IBOutlet weak var arrivalTimeLabel: UILabel!
    @IBOutlet weak var arrivalTimeButton: UIButton!
    @IBOutlet weak var leaveTimeButton: UIButton!
    @IBOutlet weak var searchAddressButton: UIButton!


    /* Overriding Super-Functions */
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        // This is needed.... i don't know why..
        mapView.delegate = self

        //Delegate textField to Self
        addressTextField.delegate = self

        //Dismiss Keyboard on view Touch
        //Looks for single or multiple taps.
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
        self.mapView.addGestureRecognizer(tap)
        //Delegate GestureRecognizer to self
        tap.delegate = self

        //Get the users current location and zoom to it
        //Authorization stuff #privacy
        self.locationManager.requestWhenInUseAuthorization()
        //initialize the updating of the location
        if(CLLocationManager.locationServicesEnabled()){
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
            locationManager.startUpdatingLocation()
        }

        //Adding TextViewListener
        addressTextField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)

        //Registering PresentNavigationViewControllerObserver :3
        NotificationCenter.default.addObserver(self, selector: #selector(self.enableNavigationMode), name: NSNotification.Name(rawValue: "StartNavigation"), object: nil)
    }
 func enableNavigationMode(){
        //Hiding some elements here
        startNavigation() //Gets called properly
    }


    func navProgressDidChange(_ userInfo: NSNotification){
        print("depart")
        print(userInfo)
    }

    func startNavigation(){
        //Get the JSON File via the MapBox API
        var lat = locationManager.location?.coordinate.latitude
        var long = locationManager.location?.coordinate.longitude
        var depart = CLLocation(latitude: lat!, longitude: long!)
        var start = Waypoint(coordinate: CLLocationCoordinate2D(latitude: lat!, longitude: long!))
        var end = Waypoint(coordinate: CLLocationCoordinate2D(latitude: Shared.shared.selectedParkhouse.latitude, longitude: Shared.shared.selectedParkhouse.longitude))

        var string = "https://api.mapbox.com/directions/v5/mapbox/driving-traffic/" + String(describing: long!) + "%2C" + String(describing: lat!) + "%3B" + String(describing: Shared.shared.selectedParkhouse.longitude) + "%2C" + String(describing: Shared.shared.selectedParkhouse.latitude) + ".json?access_token=mykey;)&steps=true"

//Alamofire request works properly
        Alamofire.request(string).responseData { response in
            if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {

                let jsoninput = self.convertToDictionary(text: utf8Text)!
                let jsonroute = (jsoninput["routes"] as! [AnyObject]).first as! [String:Any]

                let route = Route(json: jsonroute, waypoints: [start, end], profileIdentifier: MBDirectionsProfileIdentifierAutomobileAvoidingTraffic)
                let routecontroller = RouteController(route: route)

                print("regging")
                NotificationCenter.default.addObserver(RouteControllerAlertLevelDidChange, selector: #selector(self.navProgressDidChange(_:)), name: RouteControllerAlertLevelDidChange, object: routecontroller)
                print("resuming")
                routecontroller.resume()
                print("updating(?)")
                //Everything is fine until this function gets called and
                //MapBoxNavigation.swift posts a Notification   

                routecontroller.locationManager(routecontroller.locationManager, didUpdateLocations: [depart])

            }
        }
    }

我已经使用了NotificationCenter几次,这就是我来这里寻求帮助的原因。我还尝试了从navProgressDidChange(userInfo: Notification)以外的参数到我代码中当前的参数不同的函数名称和参数。我不知道为什么会发生这种情况,这在我的脑海里也没有意义,因为选择器对我来说似乎很好。

如果您需要更多信息,请询问。 谢谢你的每一个答案!!

1 个答案:

答案 0 :(得分:3)

此处的语法不正确:

NotificationCenter.default.addObserver(RouteControllerAlertLevelDidChange, selector: #selector(self.navProgressDidChange(_:)), name: RouteControllerAlertLevelDidChange, object: routecontroller)

您正在为通知订阅字符串RouteControllerAlertLevelDidChange。您打算订阅self。您可以在错误消息中看到:

app[49184:2686603] -[__NSCFConstantString navProgressDidChange:]: unrecognized selector sent to instance 0x1096dfdb0

它正在抱怨它正在尝试将消息发送到一个常量字符串。