2017-01-24 11 views
0

알림을 사용하여 한 VC에서 다른 VC로 사용자 입력 좌표의 데이터를 전달하려고합니다. 코드를 실행하면 MapView에 주석이 추가되지 않으므로 입력 된 좌표와 함께 보낼 알림을 설정하지 않았을 수도 있습니다.하지만 잘못 된 부분을 잘 모릅니다.알림 센터를 사용하여보기 컨트롤러간에 데이터 전달

좌표 입력 얻어

클래스 파일 : 통지를 수신 장소

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) 

    } 


} 

클래스 파일을 주석 : 그것은 대물-C의 API와 동일하지만 스위프트 신택스를 사용

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

.

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

또는 스위프트 3

:

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

당신의 관찰자가 목표 - C 객체에서 상속하지 않는 경우, 당신은 선택기로 사용하기 위해 @objc 와 방법을 접두사해야한다 .

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

}

+0

MapViewController의 viewDidLoad에 Observer를 추가하고 func에 @obj 접두사를 추가했지만 여전히 좌표를 전달하지 않습니다. – Kevin

0

등록 obeserver 또한 NSNotificationuserInfo 속성을 사용하여 데이터를 전송하거나 사용자 지정 개체를 사용하여 보낼 수 있습니다 MapViewController

override func viewDidLoad() { 

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

에 알림을받을 수 있습니다.

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 버전을 viewDidLoad로 추가했습니다. 좌표는 아직 지나지 않았습니다. 알림을 올바르게 설정할 수 있습니까? 그러나 코드가 좌표를 해석하기에 올바르지 않습니다. – Kevin

+0

판매자는 #selector (self.add (_ :))로 작성해야합니다. – Sahil