Passing custom data with map pin segue - ios

I've been having trouble figuring out how to pass a custom variable in a map pin to another view controller in Swift. I know that passing the coordinates, title, and subtitle are available when you addAnnotation. I would like to try and pass a custom variable but hidden. Is there such a thing? Below I am getting the users location, mapping it, dropping a pin of a couple locations nearby with annotations which goes to another view controller and passes just the title and subtitle. Any insight is greatly appreciated.
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
var mappedCity = String()
var mappedState = String()
var manager = CLLocationManager()
var annotation:MKAnnotation!
var error:NSError!
var pointAnnotation:MKPointAnnotation!
var pinAnnotationView:MKPinAnnotationView!
var selectedAnnotation: MKPointAnnotation!
private var mapChangedFromUserInteraction = false
#IBOutlet var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
self.mapView.delegate = self
self.navigationItem.titleView = searchController.searchBar
self.definesPresentationContext = true
if CLLocationManager.locationServicesEnabled(){
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestWhenInUseAuthorization()
manager.startUpdatingLocation()
}
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userLocation:CLLocation = locations[0]
let latitude = userLocation.coordinate.latitude
let longitude = userLocation.coordinate.longitude
let latDelta:CLLocationDegrees = 0.05
let lonDelta:CLLocationDegrees = 0.05
let span:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, lonDelta)
let location:CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)
let region:MKCoordinateRegion = MKCoordinateRegionMake(location, span)
self.mapView.setRegion(region, animated: true)
self.mapView.showsUserLocation = true
CLGeocoder().reverseGeocodeLocation(userLocation) { (placemarks, error) in
if (error != nil){
print(error)
}else {
if let p = placemarks?[0]{
let locality = p.locality ?? ""
let administrativeArea = p.administrativeArea ?? ""
self.mappedCity = String(locality)
self.mappedState = String(administrativeArea)
self.parseJSON("\(locality)", state: "\(administrativeArea)")
}
}
}
self.manager.stopUpdatingLocation()
}
func parseJSON(city: String, state: String){
let passedCity = city
let passedState = state
let escapedCity = passedCity.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
let escapedState = passedState.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
let url = NSURL(string:"http://www.API.com/api.php?city=\(escapedCity)&stateAbv=\(escapedState)")!
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url) { (items, response, error) -> Void in
if error != nil {
print(error)
}else {
if let items = items {
do {
let jsonResult = try NSJSONSerialization.JSONObjectWithData(items, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
if jsonResult.count > 0 {
if let datas = jsonResult["data"] as? NSArray{
for data in datas{
if let title = data["title"] as? String {
if let street = data["street"] as? String {
if let city = data["city"] as? String {
if let stateAbv = data["stateAbv"] as? String {
if let zip = data["zip"] as? String {
self.geoAddress("\(title)", street: "\(street)", city: "\(city)", state: "\(stateAbv)", zip: "\(zip)")
}
}
}
}
}
}
}
}
} catch{}
}
}
}
task.resume()
}
func geoAddress(title: String, street: String, city: String, state: String, zip: String){
let storeName = "\(title)"
let location = "\(street) \(city) \(state) \(zip)"
let geocoder = CLGeocoder();
geocoder.geocodeAddressString(location, completionHandler: {(placemarks: [CLPlacemark]?, error: NSError?) -> Void in
if (error != nil) {
print("Error \(error!)")
} else if let placemark = placemarks?[0] {
let coordinates:CLLocationCoordinate2D = placemark.location!.coordinate
let pointAnnotation:MKPointAnnotation = MKPointAnnotation()
pointAnnotation.coordinate = coordinates
pointAnnotation.title = storeName
pointAnnotation.subtitle = location
self.mapView.addAnnotation(pointAnnotation)
}
})
}
private func mapViewRegionDidChangeFromUserInteraction() -> Bool {
let view: UIView = self.mapView.subviews[0] as UIView
// Look through gesture recognizers to determine whether this region change is from user interaction
if let gestureRecognizers = view.gestureRecognizers {
for recognizer in gestureRecognizers {
if( recognizer.state == UIGestureRecognizerState.Began || recognizer.state == UIGestureRecognizerState.Ended ) {
return true
}
}
}
return false
}
func mapView(mapView: MKMapView, regionWillChangeAnimated animated: Bool) {
mapChangedFromUserInteraction = mapViewRegionDidChangeFromUserInteraction()
if (mapChangedFromUserInteraction) {
// user changed map region
}
}
func mapView(mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
if (mapChangedFromUserInteraction) {
// user changed map region
let center = mapView.centerCoordinate
let mapLatitude = center.latitude
let mapLongitude = center.longitude
let locationmove = CLLocation(latitude: mapLatitude, longitude: mapLongitude)
CLGeocoder().reverseGeocodeLocation(locationmove) { (placemarks, error) in
if (error != nil){
print(error)
}else {
if let p = placemarks?[0]{
let locality = p.locality ?? ""
let administrativeArea = p.administrativeArea ?? ""
self.mappedCity = String(locality)
self.mappedState = String(administrativeArea)
self.parseJSON("\(locality)", state: "\(administrativeArea)")
}
}
}
}
}
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
if annotation is MKUserLocation {
return nil
}
let reuseId = "pin"
var pinView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId) as? MKPinAnnotationView
if pinView == nil {
pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
pinView?.animatesDrop = false
pinView?.canShowCallout = true
pinView?.draggable = true
pinView?.pinTintColor = UIColor.greenColor()
let rightButton: AnyObject! = UIButton(type: UIButtonType.DetailDisclosure)
pinView?.rightCalloutAccessoryView = rightButton as? UIView
}
else {
pinView?.annotation = annotation
}
return pinView
}
func mapView(mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
if control == view.rightCalloutAccessoryView {
selectedAnnotation = view.annotation as? MKPointAnnotation
performSegueWithIdentifier("Details", sender: self)
}
}
func mapView(mapView: MKMapView, annotationView view: MKAnnotationView, didChangeDragState newState: MKAnnotationViewDragState, fromOldState oldState: MKAnnotationViewDragState) {
if newState == MKAnnotationViewDragState.Ending {
let droppedAt = view.annotation?.coordinate
print(droppedAt)
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "Details"){
let myDetails = segue.destinationViewController as! DetailViewController
myDetails.mytitle = selectedAnnotation.title
myDetails.mysubtitle = selectedAnnotation.subtitle
}
}
func updateSearchResultsForSearchController(searchController: UISearchController) {
}
}

Subclass the "MKPointAnnotation" class and add your custom property in it.
class MyAnnotation : MKPointAnnotation {
var customProperty : String?
}
And you can use MyAnnotation instead of MKPointAnnotation. Like following
let pointAnnotation:MyAnnotation = MyAnnotation()
pointAnnotation.coordinate = coordinates
pointAnnotation.title = storeName
pointAnnotation.subtitle = location
pointAnnotation.customProperty = "your value"
self.mapView.addAnnotation(pointAnnotation)

Related

Swift MKMapView Pin Annotation Issue

I'm trying to display pins on a map, with a preset search parameter. On a button click, the app displays all of the local taxi services. That part I have down...I have the items appending to an [MKPointAnnotation], and it successfully displays a populated list in the tableView as well as pins on the mapView. For some reason I can't get the title and subtitle to display when you tap on the pin on the mapView, even when implementing the viewFor annotation: delegate. Any ideas?
class MapViewController: UIViewController, CLLocationManagerDelegate, UITableViewDataSource, UITableViewDelegate, MKMapViewDelegate {
#IBOutlet weak var mapView: MKMapView!
#IBOutlet weak var tableView: UITableView!
let locationManager = CLLocationManager()
let regionRadius: CLLocationDistance = 1500
var matchingItems: [MKMapItem] = [MKMapItem]()
var annotationGroup = [MKPointAnnotation]()
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
tableView.delegate = self
tableView.dataSource = self
mapView.delegate = self
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
tableView.allowsSelection = true
let currentLocation = locationManager.location
guard let latitude = currentLocation?.coordinate.latitude,
let longitude = currentLocation?.coordinate.longitude else {
alertPopup(title: "Enable Location Services", message: "Navigate to Settings >", buttonTitle: "Ok")
return
}
let initialLocation = CLLocation(latitude: latitude, longitude: longitude)
tabBarController?.tabBar.isHidden = true
centerMapOnLocation(location: initialLocation)
let request = MKLocalSearchRequest()
request.naturalLanguageQuery = "Taxi"
request.region = mapView.region
let search = MKLocalSearch(request: request)
search.start(completionHandler: {(response, error) in
if error != nil {
print("Error occured in search: \(error!.localizedDescription)")
} else if response!.mapItems.count == 0 {
print("No Matches Found")
} else {
print("Matches Found")
}
for location in response!.mapItems {
print("Name = \(String(describing: item.name))")
print("Phone = \(String(describing: item.phoneNumber))")
self.matchingItems.append(item)
var pinAnnotationView = MKPinAnnotationView()
let annotation = MKPointAnnotation()
annotation.coordinate.longitude = location.placemark.coordinate.longitude
annotation.coordinate.latitude = location.placemark.coordinate.latitude
annotation.title? = location.name!
annotation.subtitle = location.phoneNumber!
self.annotationGroup.append(annotation)
self.mapView.addAnnotations(self.annotationGroup)
pinAnnotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: nil)
self.mapView.addAnnotation(pinAnnotationView.annotation!)
}
self.tableView.reloadData()
print("Reloaded Table Data")
print(self.matchingItems)
self.mapView.showAnnotations(self.annotationGroup, animated: true)
})
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if !(annotation is MKUserLocation) {
let pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: String(annotation.hash))
let rightButton = UIButton(type: .contactAdd)
rightButton.tag = annotation.hash
pinView.animatesDrop = true
pinView.canShowCallout = true
pinView.rightCalloutAccessoryView = rightButton
return pinView
} else {
print("Returned nil")
return nil
}
}
}
The issue is the optional annotation.title? = location.name!. Remove the optional and it works.
for location in response!.mapItems {
print("Name = \(String(describing: location.name))")
print("Phone = \(String(describing: location.phoneNumber))")
self.matchingItems.append(location)
let annotation = MKPointAnnotation()
annotation.coordinate.longitude = location.placemark.coordinate.longitude
annotation.coordinate.latitude = location.placemark.coordinate.latitude
annotation.title = location.name! //This is the line to remove the optional annotation.title? from.
annotation.subtitle = location.phoneNumber!
self.annotationGroup.append(annotation)
self.mapView.addAnnotations(self.annotationGroup)
self.mapView.showAnnotations(self.annotationGroup, animated: true)
}
Maybe is too late but anyway
First of all, MKAnnotation is a protocol so I think that you must define a custom class for your objects, and this class must implement this protocol or in this case we can define an extension for MKMapItem implementing MKAnnotation protocol
extension MKMapItem : MKAnnotation
{
public var coordinate: CLLocationCoordinate2D {
return self.placemark.coordinate
}
// Title and subtitle for use by selection UI.
public var title: String? {
return self.name
}
public var subtitle: String? {
return self.phoneNumber
}
}
with this your code will be reduced to this
search.start(completionHandler: {(response, error) in
if error != nil {
print("Error occured in search: \(error!.localizedDescription)")
} else if response!.mapItems.count == 0 {
print("No Matches Found")
} else {
print("Matches Found")
}
for location in response!.mapItems {
print("Name = \(String(describing: item.name))")
print("Phone = \(String(describing: item.phoneNumber))")
self.matchingItems.append(item)
}
self.mapView.addAnnotations(self.matchingItems)
self.tableView.reloadData()
print("Reloaded Table Data")
print(self.matchingItems)
self.mapView.showAnnotations(self.matchingItems, animated: true)
})
Once you have this then your implementation of func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {} should work
Hope this helps

Memory leak in Swift app due to ContiguousArrayStorage

I'm designing an app which has the a feature to let user add their own pin. Recently, I found my app has a memory leak with the title of "ContiguousArrayStorage". I debugged a little and figured out it was a problem with my for loop in my viewdidload, but I am not sure how to fix the leak.
Here is my code:
#IBOutlet weak var AppleMap: MKMapView!
#IBOutlet weak var LogoutOutlet: UIButton!
#IBOutlet weak var OutletforAddPokemon: UIButton!
#IBOutlet weak var FindLocationOutlet: UIButton!
#IBOutlet weak var FilterOutlet: UIButton!
let locationManager = CLLocationManager()
let calendar: NSCalendar! = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
var increment:Int = 0
var currentLoc:CLLocationCoordinate2D?
var centerMap = true
let StoringPin = FIRDatabase.database().reference().child("locations")
var Date = NSDate()
override func viewDidLoad() {
super.viewDidLoad()
AppleMap.delegate = self
StoringPin.observeEventType(.Value, withBlock: {
snapshot in
if snapshot.value is NSNull {
return
}
let val = snapshot.value as! [String : [String : AnyObject]]
for key in val.keys {
let latitudedata = val[key]!["latitude"] as! Double
let longitudedata = val[key]!["longitude"] as! Double
let namedata = val[key]!["name"] as! String
let Username = val[key]!["Username"]
as! String
let DATE = val[key]!["Date"]
as! String
let NumberOflikesforuser = val[key]!["Likes"] as! Int
let NumberOfDislikesforuser = val[key]!["Dislikes"] as! Int
let coord = CLLocationCoordinate2D(latitude: latitudedata, longitude: longitudedata)
let artwork = Capital(title: "\(namedata)", coordinate: coord, info: "HI", username: Username, NumofLikes: NumberOflikesforuser,NumofDisLikes: NumberOfDislikesforuser, UIDSTring: UID, date: DATE, color: MKPinAnnotationColor.Green)
artwork.subtitle = DATE
print("k")
let permastringforemail:String = Username
print(++self.increment)
print(UID)
print(permastringforemail)
stringforemail = permastringforemail
Arrayforpins.append(artwork)
self.AppleMap.addAnnotation(Arrayforpins[Arrayforpins.count - 1])
for Capital in Arrayforpins {
self.AppleMap.addAnnotation(Capital)
}
}
})
print(LogoutOutlet)
LogoutOutlet.layer.cornerRadius = 4
FindLocationOutlet.layer.cornerRadius = 4
OutletforAddPokemon.layer.cornerRadius = 4
//FilterOutlet.layer.cornerRadius = 4
self.locationManager.requestAlwaysAuthorization()
self.locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.startUpdatingLocation()
}
let annotationView = MKAnnotationView()
let detailButton: UIButton = UIButton.init(type: .DetailDisclosure) as UIButton
annotationView.rightCalloutAccessoryView = detailButton
}
let regionRadius: CLLocationDistance = 1000
func centerMapOnLocation(location: CLLocation) {
let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate,
regionRadius * 2.0, regionRadius * 2.0)
AppleMap.setRegion(coordinateRegion, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let locValue:CLLocationCoordinate2D = manager.location!.coordinate
if CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse {
AppleMap.showsUserLocation = true
} else {
locationManager.requestWhenInUseAuthorization()
}
print("update")
currentLoc = locValue
if centerMap {
centerMap = false
centerMapOnLocation(CLLocation(latitude: currentLoc!.latitude, longitude: currentLoc!.longitude))
}
}
#IBAction func SendtoSelector(sender: AnyObject) {
self.performSegueWithIdentifier("SeguetoSelector", sender: self)
}
#IBAction func FilterFunc(sender: AnyObject) {
self.performSegueWithIdentifier("SeguetoFilter", sender: self)
}
#IBAction func FindLocation(sender: AnyObject) {
centerMapOnLocation(CLLocation(latitude: currentLoc!.latitude, longitude: currentLoc!.longitude))
}
#IBAction func Logout(sender: AnyObject) {
LO = true
self.performSegueWithIdentifier("BacktoLoginScreen", sender: self)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
locationManager
if IndexBoolean == true{
//let annotationView = MKPinAnnotationView()
print("Hi")
let artwork = Capital(title: "\(pickerDataSource[chosenindex])", coordinate: CLLocationCoordinate2D(latitude: currentLoc!.latitude, longitude: currentLoc!.longitude), info: "HEY", username: stringforemail, NumofLikes: NumberOfLikes, NumofDisLikes: NumberOfDislike, UIDSTring: UID, date: stringfordate2, color: MKPinAnnotationColor.Green)
//print(now)
print(chosenindex)
artwork.title = "\(pickerDataSource[chosenindex])"
//artwork.subtitle = stringfordate
AppleMap.addAnnotation(artwork)
//annotationView.pinColor = artwork.Green
Arrayforpins.append(artwork)
print(stringforemail)
AppleMap.addAnnotation(Arrayforpins[Arrayforpins.count - 1])
for Capital in Arrayforpins{
AppleMap.addAnnotation(Capital)
}
IndexBoolean = false
var formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZ"
formatter.timeZone = NSTimeZone(abbreviation: "Central Time")
var utcTimeZoneSTR = formatter.stringFromDate(Date)
stringfordate = "\(utcTimeZoneSTR)"
let uid = NSUUID().UUIDString
UID = uid
StoringPin.child(uid).setValue(["name" : pickerDataSource[chosenindex],
"latitude" : currentLoc!.latitude,
"longitude" : currentLoc!.longitude,"Array Position" : chosenindex,"Username": stringforemail, "Likes": NumberOfLikes2, "Dislikes":
NumberOfDislike, "UID": UID, "Date": stringfordate])
if FilterBoolean == true {
print("b")
if FilterDataSource[Intforfilter] != stringforname {
print("k")
//self.AppleMap.viewForAnnotation(artwork)?.hidden = true
FilterBoolean == false
}
//else {
// print("m")
// self.AppleMap.removeAnnotation(artwork)
//
// }
FilterBoolean == false
}
}
}
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
let identifier = "Capital"
print(++increment)
if annotation.isKindOfClass(Capital.self) {
print("CAPITAL")
if let annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(identifier) {
annotationView.annotation = annotation
return annotationView
} else {
let annotationView = MKPinAnnotationView(annotation:annotation, reuseIdentifier:identifier)
annotationView.enabled = true
annotationView.canShowCallout = true
//annotationView.pinColor = MKPinAnnotationColor.Green
let btn = UIButton(type: .DetailDisclosure)
annotationView.rightCalloutAccessoryView = btn
return annotationView
}
}
return nil
}
func mapView(mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
let capital = view.annotation as! Capital
let placeName = capital.title
let placeInfo = capital.info
let UserName = capital.username
stringforname = view.annotation!.title!!
coords = view.annotation!.coordinate
stringforemail = capital.username
stringfordate2 = capital.date
NumberOfLikes2 = capital.NumofLikes
UID = capital.UIDSTring
print(stringforname)
print(UID)
self.performSegueWithIdentifier("SegueToInfo", sender: self)
}
I note you're not taking care to specify how to capture self in your closure. When in a disposable object context (a UIViewController) and an async closure you always have to worry about this. You need to capture it as weak or unowned. Are you familiar with closure capture lists?
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/AutomaticReferenceCounting.html#//apple_ref/doc/uid/TP40014097-CH20-ID56
The pattern I use is to capture self weakly and then bail if self has become nil, e.g. the UIViewController has been dismissed and harvested. If it is still around, I temporarily capture it strongly with a local variable in a guard...let statement.
withBlock: { [weak self] (snapshot) in
guard let s = self else {
print("Callback called after view unloaded")
return
}
// now use 's' instead of 'self'
...
}
Can't say this is the only problem because we don't have the declarations for your helper classes. For example we don't know what mischief Capital is up to.
By the way, just be clear that your for loop does not run at viewDidLoad(). You're merely registering a callback that only reacts if and when the .Value event occurs on the StoringPin object.

Subview animation is affected by mapview

I am using swift and I am working on a project, where I have to show a draggable map with changing location. and below the map I have subview and it have a button, on button click the subview will appear and on same button click I will disappear.
But the problem is sometime its working fine some time this view is go down and not coming on screen. and specially when I use button title change code.
class LocationMAP: UIViewController,CLLocationManagerDelegate,MKMapViewDelegate {
#IBOutlet weak var locationLabel: UILabel!
#IBOutlet weak var selectAnyoneButton: UIButton!
#IBOutlet weak var selectingView: UIView!
var changingText:Bool = false
#IBOutlet weak var map: MKMapView!
var locationManger = CLLocationManager()
let geoCoder = CLGeocoder()
var myLocation: CLLocation!
override func viewDidLoad() {
super.viewDidLoad()
self.locationManger.delegate = self
locationManger.desiredAccuracy = kCLLocationAccuracyBest
locationManger.requestWhenInUseAuthorization()
locationManger.startUpdatingLocation()
if( CLLocationManager.authorizationStatus() == CLAuthorizationStatus.AuthorizedWhenInUse ||
CLLocationManager.authorizationStatus() == CLAuthorizationStatus.AuthorizedAlways){
}
self.map.showsUserLocation = true
self.map.delegate = self
self.map.setUserTrackingMode(MKUserTrackingMode.Follow, animated: true)
let location = CLLocationCoordinate2DMake(20.59368, 78.96288)
let span = MKCoordinateSpanMake(0.2, 0.2)
_ = MKCoordinateRegionMake(location, span)
let annotation = MKPointAnnotation()
annotation.coordinate = (location)
selectAnyoneButton.setTitle("Submit", forState: .Normal)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//MARK:- MapView Delegates
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
switch status {
case .Authorized, .AuthorizedWhenInUse:
manager.startUpdatingLocation()
self.map.showsUserLocation = true
default: break
}
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
self.myLocation = locations.last! as CLLocation
let userLocation:CLLocation = locations.last!
let long = userLocation.coordinate.longitude
let lat = userLocation.coordinate.latitude
print(long , lat)
// locationManger.stopUpdatingLocation()
self.map.centerCoordinate = myLocation.coordinate
let reg = MKCoordinateRegionMakeWithDistance(myLocation.coordinate, 1500, 1500)
self.map.setRegion(reg, animated: true)
geoCode(myLocation)
}
func geoCode(location : CLLocation!){
geoCoder.cancelGeocode()
self.locationManger.stopUpdatingLocation()
geoCoder.reverseGeocodeLocation(location, completionHandler: { (placemark, error) -> Void in
guard let placeMarks = placemark as [CLPlacemark]! else {
return
}
let loc: CLPlacemark = placeMarks[0]
let addressDict : [NSString:NSObject] = loc.addressDictionary as! [NSString: NSObject]
let addrList = addressDict["FormattedAddressLines"] as! [String]
let address = (addrList.joinWithSeparator(", "))
self.locationLabel.text = address
let lat = loc.location!.coordinate.latitude
let long = loc.location!.coordinate.longitude
print(lat , long)
SharedPreferenceManager.sharedInstance.userLatitude = lat
SharedPreferenceManager.sharedInstance.userLongitude = long
SharedPreferenceManager.sharedInstance.userAddress = address
})
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
print(error.localizedDescription)
}
func mapView(mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
let location = CLLocation(latitude: mapView.centerCoordinate.latitude, longitude: mapView.centerCoordinate.longitude)
geoCode(location)
self.map.removeAnnotations(mapView.annotations)
let annotation = MKPointAnnotation()
annotation.coordinate = map.centerCoordinate
annotation.title = "title"
annotation.subtitle = "subtitle"
self.map.addAnnotation(annotation)
}
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
let annotationView = MKPinAnnotationView()
if #available(iOS 9.0, *) {
annotationView.pinTintColor = UIColor.blueColor()
annotationView.center = CGPointMake(160, 200)
} else {
}
return annotationView
}
func mapView(mapView: MKMapView, annotationView view: MKAnnotationView, didChangeDragState
newState: MKAnnotationViewDragState, fromOldState oldState: MKAnnotationViewDragState) {
if (newState == MKAnnotationViewDragState.Starting) {
view.dragState = MKAnnotationViewDragState.Dragging
}
else if (newState == MKAnnotationViewDragState.Ending || newState == MKAnnotationViewDragState.Canceling){
view.dragState = MKAnnotationViewDragState.None
}
}
//MARK:- Button Action Methods
#IBOutlet weak var downBtn: UILabel!
#IBAction func chooseButtonAction(sender: AnyObject) {
if (changingText == false) {
let newCenter:CGPoint = CGPointMake(selectingView.center.x, selectingView.center.y - 230)
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(0.55)
selectingView.center = newCenter
UIView.commitAnimations()
selectAnyoneButton.setTitle("Select a service", forState: .Normal)
changingText = true
} else {
let newCenter:CGPoint = CGPointMake(selectingView.center.x, selectingView.center.y + 230)
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(0.55)
selectingView.center = newCenter
UIView.commitAnimations()
selectAnyoneButton.setTitle("Submit", forState: .Normal)
changingText = false
}
}
in button's action methods, add:
super.bringSubviewToFront(UIView)
towards the end.
I am assuming your view in question is a direct child of superview.

Update custom annotation pin image to standard annotation pin in swift

I want to update map view every 60 seconds & make an annotation with custom pin/image but want to show standard pin [red color - See Figure 6-1] icon to the previously drawn annotation. I tried like below code but that does not working properly. With another custom image it works but i can't show that default/standard red pin to previous annotation. Please see "currentLocationHasBeenUpdated" function where i tried to show standard red icon to the previous annotation. Please let me know how can i achieve this. Thanks.
My ViewController :
import UIKit
import MapKit
class FirstTabController: UIViewController, MKMapViewDelegate, DelegateForUpdateCurrentLocation {
#IBOutlet weak var mapView: MKMapView!
var gpsLocations : [[String: AnyObject]]!
var dataManager : DataManager!
var currentAnnotation : MKAnnotation!
//Return CLLocation Coordinate
func getLocationObject(latitude:Double, longitude:Double) -> CLLocationCoordinate2D {
return CLLocationCoordinate2D(
latitude: latitude,
longitude: longitude
)
}
//Create annotation object & return
func createAnnotation(latitude:Double, longitude:Double, locationName:String, territory:String) -> MKPointAnnotation {
let annotation = MKPointAnnotation()
annotation.coordinate = self.getLocationObject(latitude, longitude: longitude)
annotation.title = locationName
annotation.subtitle = territory
return annotation
}
//Create annotaion for current ship position
func createAnnotationForCurrentPosition(location:[String: AnyObject]) -> MKPointAnnotation {
let latitude = (location["latitude"] as? Double)!
let longitude = (location["longitude"] as? Double)!
let name = (location["locationName"] as? String)!
let territory = (location["territory"] as? String)!
return self.createAnnotation(latitude, longitude: longitude, locationName: name, territory: territory)
}
//Set region on map view
func setRegion(location:[String: AnyObject]){
let latitude = (location["latitude"] as? Double)!
let longitude = (location["longitude"] as? Double)!
let location = self.getLocationObject(latitude, longitude: longitude)
//Set zoom span
let span = MKCoordinateSpanMake(0.05, 0.05)
//Create region on map view & show
let region = MKCoordinateRegion(center: location, span: span)
self.mapView.setRegion(region, animated: true)
}
//This function will fire from data manager when current location from API has been updated
func currentLocationHasBeenUpdated(location:[String: AnyObject]){
dispatch_async(dispatch_get_main_queue()){
if self.currentAnnotation != nil {
var currentAnnotationView = self.mapView.viewForAnnotation(self.currentAnnotation)
if currentAnnotationView != nil {
currentAnnotationView.image = nil //this line makes app crash [gave nil to show standard red icon]
// currentAnnotationView.image = UIImage(named:"first") - this line works perfectly with different icon. but i don't want any custom icon except the standard red one
}
}
self.mapView.addAnnotation(self.createAnnotationForCurrentPosition(location))
self.setRegion(location)
}
}
//Update map view by scheduling time if current location is changed yet
func updateMapView() {
self.dataManager.getCurrentLocation()
}
override func viewDidLoad() {
super.viewDidLoad()
//Get gps locations from data manager
self.dataManager = DataManager()
self.dataManager.delegate2 = self
self.dataManager.getCurrentLocation()
//self.mapView.userTrackingMode = MKUserTrackingMode.FollowWithHeading
//Get GPS location by scheduling time
NSTimer.scheduledTimerWithTimeInterval(60, target: self, selector: Selector("updateMapView"), userInfo: nil, repeats: true)
}
func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer!{
if overlay is MKPolyline {
var polylineRenderer = MKPolylineRenderer(overlay: overlay)
polylineRenderer.strokeColor = UIColor.blueColor()
polylineRenderer.lineWidth = 2
return polylineRenderer
}
return nil
}
//Make custom annotaion pin if the annotation is of ship's current position
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView!{
println("Hello")
self.currentAnnotation = annotation
//Custom annotation view with custom pin icon
let reuseId = "custom"
var annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId)
if annotationView == nil {
annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
annotationView.canShowCallout = true
}
else {
annotationView.annotation = annotation
}
//Set annotation specific properties after the view is dequeued or created...
annotationView.image = UIImage(named:"pinicon")
return annotationView
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
and for coordinates from api
import Foundation
extension String {
func toDouble() -> Double? {
return NSNumberFormatter().numberFromString(self)?.doubleValue
}
}
class DataSet{
var settings : Settings!
var getService : GetService!
var currentLocation : [String: AnyObject]!
//Object initialization for API call
init(){
self.settings = Settings()
self.getService = GetService()
}
func getCurrentLocation(callback:([String: AnyObject]) -> ()){
self.getService.apiCallToGet(self.settings.getCoordinates(), callback: {
(response) in
var location = [String: AnyObject]()
for item in response {
if let dictionary = item as? NSDictionary {
if let lat = dictionary["Lat"] as? String {
if lat.toDouble() != nil {
location["latitude"] = lat.toDouble()!
}
}
if let long = dictionary["Long"] as? String {
if long.toDouble() != nil {
location["longitude"] = long.toDouble()!
}
}
if let name = dictionary["Name"] as? String {
location["locationName"] = name
}
if let territory = dictionary["Territory"] as? String {
location["territory"] = territory
}
println(location["latitude"]!)
println(location["longitude"]!)
if self.currentLocation != nil {
if ((self.currentLocation["latitude"] as? Double) != (location["latitude"] as? Double)) && ((self.currentLocation["longitude"] as? Double) != (location["longitude"] as? Double)){
self.currentLocation = location
callback(location)
}
} else {
self.currentLocation = location
callback(location)
}
}
}
})
}
}
I have solved my problem by creating custom annotation class like below -
import UIKit
import MapKit
var ARROW_ANNOTATION : NSString = "ARROW_ANNOTATION"
var PIN_ANNOTATION : NSString = "PIN_ANNOTATION"
class Annotation: NSObject, MKAnnotation {
var currentLocation: CLLocationCoordinate2D
var _title : String
var subTitle : String
var direction : CLLocationDirection!
var typeOfAnnotation : String!
init(coordinate: CLLocationCoordinate2D, title : String, subTitle : String) {
self.currentLocation = coordinate
self._title = title
self.subTitle = subTitle
}
func getLocation() -> CLLocation {
return CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude)
}
var coordinate: CLLocationCoordinate2D {
return self.currentLocation
}
var title : String {
return self._title
}
var subtitle : String {
return self.subTitle
}
}
and In my ViewController file -
override func viewDidLoad() {
super.viewDidLoad()
var annotation1 : Annotation = Annotation(coordinate: location, title: name, subTitle: territory)
annotation.typeOfAnnotation = PIN_ANNOTATION as String
self.mapView.addAnnotation(annotation1)
var annotation2 : Annotation = Annotation(coordinate: location, title: name, subTitle: territory)
annotation.typeOfAnnotation = ARROW_ANNOTATION as String
self.mapView.addAnnotation(annotation2)
}
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView!{
let reuseId = "custom"
var annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId)
var customAnnotationView : MKAnnotationView!
if let _annotation = annotation as? Annotation {
if _annotation.typeOfAnnotation == PIN_ANNOTATION {
customAnnotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
customAnnotationView.canShowCallout = true
//customAnnotationView.draggable = true
} else {
customAnnotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
// 17 - Determine the direction
let arrowImage = UIImage(named:"arrow")!
let direction = _annotation.direction
customAnnotationView.image = self.rotatedImage(arrowImage, byDegreesFromNorth: direction)
customAnnotationView.canShowCallout = true
}
} else {
return nil
}
return customAnnotationView
}

How to add a button to the MKPointAnnotation?

I've just got stuck trying to add a detail button to my annotation point, unfortunately I don't know how to do it. Does anyone could help me with that?
The image below presents what I'd like to achieve. Thanks!
MapKitViewController:
import UIKit
import MapKit
import CoreLocation
class MapKitViewController: UIViewController, MKMapViewDelegate
{
let locationManager = CLLocationManager()
#IBOutlet weak var nmapView: MKMapView!
override func viewDidLoad()
{
super.viewDidLoad()
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
let location = CLLocationCoordinate2D(
latitude: 53.4265107,
longitude: 14.5520357)
let span = MKCoordinateSpanMake(0.05, 0.05)
let region = MKCoordinateRegion(center: location, span: span)
nmapView.setRegion(region, animated: true)
nmapView.showsPointsOfInterest = false
nmapView.showsUserLocation = true
displayMarkers()
}
func displayMarkers() -> Void
{
let jsonURL: NSURL = NSURL(string: "http://jsonstring.com/")!
var dataFromNetwork: NSData = NSData(contentsOfURL: jsonURL)!
let json = JSON(data: dataFromNetwork)
var jsonSize = json.count
var todaysDate:NSDate = NSDate()
var dateFormatter:NSDateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
var formattedDate:String = dateFormatter.stringFromDate(todaysDate)
let annotationView = MKAnnotationView()
let detailButton: UIButton = UIButton.buttonWithType(UIButtonType.DetailDisclosure) as UIButton
annotationView.rightCalloutAccessoryView = detailButton
for(var i = 0; i < jsonSize; i++)
{
if(json[i]["rozpoczecie"].stringValue == formattedDate)
{
let clubID = json[i]["id_klub"].stringValue
let annotation = MKPointAnnotation()
let (resultSet, err) = SD.executeQuery("SELECT * FROM Clubs WHERE ID = ?", withArgs: [clubID])
if(err != nil){println("blad")}
else
{
for row in resultSet
{
let name = row["Name"]?.asString()
let latitude = row["Latitude"]?.asDouble()
let longitude = row["Longitude"]?.asDouble()
annotation.title = name
var markerLatitude: Double = latitude!
var markerLongitude: Double = longitude!
let location = CLLocationCoordinate2D(latitude: markerLatitude, longitude: markerLongitude)
annotation.setCoordinate(location)
annotation.subtitle = json[i]["nazwa"].stringValue
}
nmapView.addAnnotation(annotation)
}
}
}
}
You are doing it right.You just need to have these methods implemented for adding button along with title and subtitle
iOS 8 and Xcode 6
import UIKit
import MapKit
import CoreLocation
class MapKitViewController: UIViewController, MKMapViewDelegate
{
let locationManager = CLLocationManager()
#IBOutlet weak var nmapView: MKMapView!
override func viewDidLoad()
{
super.viewDidLoad()
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
let location = CLLocationCoordinate2D(
latitude: 53.4265107,
longitude: 14.5520357)
let span = MKCoordinateSpanMake(0.05, 0.05)
let region = MKCoordinateRegion(center: location, span: span)
nmapView.setRegion(region, animated: true)
nmapView.showsPointsOfInterest = false
nmapView.showsUserLocation = true
displayMarkers()
}
// When user taps on the disclosure button you can perform a segue to navigate to another view controller
func mapView(mapView: MKMapView!, annotationView view: MKAnnotationView!, calloutAccessoryControlTapped control: UIControl!) {
if control == view.rightCalloutAccessoryView{
println(view.annotation.title) // annotation's title
println(view.annotation.subtitle) // annotation's subttitle
//Perform a segue here to navigate to another viewcontroller
// On tapping the disclosure button you will get here
}
}
// Here we add disclosure button inside annotation window
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
println("viewForannotation")
if annotation is MKUserLocation {
//return nil
return nil
}
let reuseId = "pin"
var pinView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId) as? MKPinAnnotationView
if pinView == nil {
//println("Pinview was nil")
pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
pinView!.canShowCallout = true
pinView!.animatesDrop = true
}
var button = UIButton.buttonWithType(UIButtonType.DetailDisclosure) as UIButton // button with info sign in it
pinView?.rightCalloutAccessoryView = button
return pinView
}
func displayMarkers() -> Void
{
let jsonURL: NSURL = NSURL(string: "http://atnight.wtznc.com/json.php")!
var dataFromNetwork: NSData = NSData(contentsOfURL: jsonURL)!
let json = JSON(data: dataFromNetwork)
var jsonSize = json.count
var todaysDate:NSDate = NSDate()
var dateFormatter:NSDateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
var formattedDate:String = dateFormatter.stringFromDate(todaysDate)
let annotationView = MKAnnotationView()
// Adding button here wont do anything so remove these two lines
let detailButton: UIButton = UIButton.buttonWithType(UIButtonType.DetailDisclosure) as UIButton
annotationView.rightCalloutAccessoryView = detailButton
// For adding button we have to use a method named as viewForAnnotation
for(var i = 0; i < jsonSize; i++)
{
if(json[i]["rozpoczecie"].stringValue == formattedDate)
{
let clubID = json[i]["id_klub"].stringValue
let annotation = MKPointAnnotation()
let (resultSet, err) = SD.executeQuery("SELECT * FROM Clubs WHERE ID = ?", withArgs: [clubID])
if(err != nil){println("blad")}
else
{
for row in resultSet
{
let name = row["Name"]?.asString()
let latitude = row["Latitude"]?.asDouble()
let longitude = row["Longitude"]?.asDouble()
annotation.title = name
var markerLatitude: Double = latitude!
var markerLongitude: Double = longitude!
let location = CLLocationCoordinate2D(latitude: markerLatitude, longitude: markerLongitude)
annotation.setCoordinate(location)
annotation.subtitle = json[i]["nazwa"].stringValue
}
nmapView.addAnnotation(annotation)
}
}
}
}
}
Check out my output.

Resources