Having some trouble getting the annotation to appear on the map. The address string is getting passed in from the previous ViewController. Everything working fine up to pushing the annotation to the map. Any suggestions?
class PostViewController: UIViewController {
@IBOutlet weak var locationInput: UITextField!
@IBOutlet weak var debugText: UILabel!
@IBAction func postDirectionTouched(sender: AnyObject) {
if locationInput.text!.isEmpty {
debugText.text = "Location Input Empty."
} else {
nextSegue()
}
}
func nextSegue() {
dispatch_async(dispatch_get_main_queue(), {
let controller = self.storyboard!.instantiateViewControllerWithIdentifier("LinkPostController") as! LinkPostViewController
controller.address = self.locationInput.text!
self.presentViewController(controller, animated: true, completion: nil)
})
}
}
import UIKit
import CoreLocation
import AddressBook
import MapKit
class LinkPostViewController: UIViewController, MKMapViewDelegate {
@IBOutlet weak var pointMap: MKMapView!
@IBOutlet weak var linkInput: UITextField!
@IBOutlet weak var debugText: UILabel!
var address: String = ""
var coords: CLLocationCoordinate2D?
override func viewDidLoad() {
super.viewDidLoad()
self.mapLocation()
}
func mapLocation(){
let geocoder = CLGeocoder()
geocoder.geocodeAddressString(self.address, completionHandler: {(placemark, error) -> Void in
if error != nil{
print("Geocode failed with error: \(error!.localizedDescription)")
} else if placemark!.count > 0 {
let pm = placemark?[0]
let location = pm!.location
self.coords = location!.coordinate
print(self.coords!)
self.showMap()
}
})
}
func showMap() {
print("last")
let coordinates = self.coords
let pinn = MKPointAnnotation()
pinn.title = "hello"
pinn.subtitle = "This my pin."
pinn.coordinate = coordinates!
dispatch_async(dispatch_get_main_queue()) {
self.pointMap.addAnnotation(pinn)
}
}
func mapView(mapView: MKMapView, annotationView: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {}
}
Simplest working example, adds an annotation in Australia:
import UIKit
import MapKit
class ViewController: UIViewController {
// MARK: - Private variables
private var mapView: MKMapView?
// MARK: - UIViewController methods
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
mapView = MKMapView(frame: view.frame)
view.addSubview(mapView!)
let locationCoordinate = CLLocationCoordinate2DMake(-25.27, 133.775)
let pointAnnotation = MKPointAnnotation()
pointAnnotation.coordinate = locationCoordinate
mapView?.addAnnotation(pointAnnotation)
}
}
check placemark!.count > 0 (your code looks correct)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.