2017-01-24 7 views
0

Я пытаюсь передать данные координат ввода-вывода из одного VC в другой с помощью уведомлений. Когда я запускаю код, он не добавляет аннотации в MapView, поэтому у меня есть подозрение, что я, возможно, не настроил уведомление для отправки с введенными координатами должным образом, но я не уверен, где я поступил не так.Swift Использование NotificationCenter для передачи данных между контроллерами просмотра

файл

Класс, который принимает ввод координат:

import UIKit 
import CoreLocation 

var locations: [Dictionary<String, Any>] = [] // here I initialize my empty array of locations 

class OtherVC: UIViewController { 

    @IBOutlet weak var latitudeField: UITextField! 
    @IBOutlet weak var longitudeField: UITextField! 

    @IBOutlet weak var titleTextField: UITextField! 
    var coordinates = [CLLocationCoordinate2D]() 

    override func viewDidLoad() { 
     super.viewDidLoad() 
    } 




    @IBAction func addToMap(_ sender: Any) { 
     let lat = latitudeField.text! 
     let long = longitudeField.text! 
     let title = titleTextField.text! 
     var location: [String: Any] = ["title": title, "latitude": lat, "longitude": long] 
     locations.append(location) 
     NotificationCenter.default.post(name: NSNotification.Name("MapViewController.coordinate.updated"), object: locations, userInfo: nil) 

    } 


} 

Class файл, который получает уведомление и помещает аннотацию:

import UIKit 
import MapKit 
class MapViewController: UIViewController, MKMapViewDelegate { 


    @IBOutlet weak var mapView: MKMapView! 



    override func viewDidLoad() { 
     super.viewDidLoad() 
     mapView.delegate = self 
    } 

    func add(notification: NSNotification) { 

     let dict = notification.object as! NSDictionary 

     // takes the coordinates from the notification and converts such that the map can interpret them 
     let momentaryLat = (dict["latitude"] as! NSString).doubleValue 
     let momentaryLong = (dict["longitude"] as! NSString).doubleValue 
     let annotation = MKPointAnnotation() 
     annotation.title = dict["title"] as? String 
     annotation.coordinate = CLLocationCoordinate2D(latitude: momentaryLat as CLLocationDegrees, longitude: momentaryLong as CLLocationDegrees) 
     mapView.addAnnotation(annotation) 
     self.mapView.centerCoordinate = annotation.coordinate 
    } 


    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 

    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { 
     let identifier = "pinAnnotation" 
     var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) as? MKPinAnnotationView 

    if annotationView == nil { 
     annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier) 
     annotationView?.canShowCallout = true 
    } 

    annotationView?.annotation = annotation 
    return annotationView 
    } 
} 
+0

http://stackoverflow.com/questions/36910965/how-to-pass-data-using-notificationcentre-in-swift-3-0-and-nsnotificationcenter/36911168# 36911168 – Sahil

+0

Похоже, вы не добавили наблюдателя для уведомления в свой класс MapViewController. – firstinq

ответ

1

Это так же, как Objective-C API, но использует синтаксис Свифта ,

NSNotificationCenter.defaultCenter().addObserver(
self, 
selector: #selector(batteryLevelChanged), 
name: UIDeviceBatteryLevelDidChangeNotification, 
object: nil) 

Или в Swift 3:

NotificationCenter.default.addObserver(
self, 
selector: #selector(self.batteryLevelChanged), 
name: .UIDeviceBatteryLevelDidChange, 
object: nil) 

Если наблюдатель не наследуется от объекта Objective-C, необходимо префикс ваш метод с @objc для того, чтобы использовать его в качестве селектора ,

@objc func batteryLevelChanged(notification: NSNotification){  
//do stuff 

}

+0

Я добавил наблюдателя в viewDidLoad из MapViewController, а также префикс @obj для моего func, но он по-прежнему не передает координаты. – Kevin

0

Регистрация obeserver получать уведомления в вашем MapViewController

override func viewDidLoad() { 

    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.add(_:)), name: NSNotification.Name("MapViewController.coordinate.updated"), object: nil) 
} 

Также вы можете передавать данные, используя userInfo свойство NSNotification или отправить с помощью пользовательского объекта.

func add(_ notification: NSNotification) { 
... 
} 

см pass data using nsnotificationcenter

+0

Я добавил наблюдателя - NotificationCenter.default.addObserver (self, selector: #selector (self.add), имя: NSNotification.Name ("MapViewController.coordinate.updated"), object: nil) - версия Swift 3.0 для просмотраDidLoad , и координата все еще не прошла. Могут ли уведомления быть настроены правильно, но мой код не подходит для интерпретации координат? – Kevin

+0

Селектор должен быть записан как #selector (self.add (_ :)). – Sahil