This problem is absolutely driving me insane, and I've searched all over with no luck finding a solution. Please forgive what is probably a basic question...
I followed a tutorial to make a simple Geofence application. Problem is, my MKMapView keeps giving me a nil variable when I declare it, giving me the "unexpectedly found nil while unwrapping an Optional value" error.
The variable in question is mapView, and the line that's giving me an issue is mapView.delegate = self
Here's my code:
import UIKit
import CoreLocation
import MapKit
class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
#IBOutlet weak var mapView: MKMapView!
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
// setup locationManager
locationManager.delegate = self
locationManager.distanceFilter = kCLLocationAccuracyNearestTenMeters
locationManager.desiredAccuracy = kCLLocationAccuracyBest
// setup mapView
mapView.delegate = self
mapView.showsUserLocation = true
mapView.userTrackingMode = .follow
// setup test data
setupData()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// status is not determined
if CLLocationManager.authorizationStatus() == .notDetermined {
locationManager.requestAlwaysAuthorization()
}
// authorization were denied
else if CLLocationManager.authorizationStatus() == .denied {
showAlert(title: "Location services were previously denied. Please enable location services for this app in Settings.")
}
// we do have authorization
else if CLLocationManager.authorizationStatus() == .authorizedAlways {
locationManager.startUpdatingLocation()
}
}
func setupData() {
// check if can monitor regions
if CLLocationManager.isMonitoringAvailable(for: CLCircularRegion.self) {
// region data
let title = "Weber"
let coordinate = CLLocationCoordinate2DMake(37.703026, -121.759735)
let regionRadius = 300.0
// setup region
let region = CLCircularRegion(center: CLLocationCoordinate2D(latitude: coordinate.latitude, longitude: coordinate.longitude), radius: regionRadius, identifier: title)
locationManager.startMonitoring(for: region)
// setup annotation
let restaurantAnnotation = MKPointAnnotation()
restaurantAnnotation.coordinate = coordinate;
restaurantAnnotation.title = "\(title)";
mapView.addAnnotation(restaurantAnnotation)
// setup circle
let circle = MKCircle(center: coordinate, radius: regionRadius)
mapView.add(circle)
}
else {
print("System can't track regions")
}
}
// MARK: - MKMapViewDelegate
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
let circleRenderer = MKCircleRenderer(overlay: overlay)
circleRenderer.strokeColor = UIColor.blue
circleRenderer.lineWidth = 1.0
return circleRenderer
}
// MARK: - CLLocationManagerDelegate
func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {
showAlert(title: "enter \(region.identifier)")
}
func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) {
showAlert(title: "exit \(region.identifier)")
}
// MARK: - Helpers
func showAlert(title: String) {
let alert = UIAlertController(title: title, message: nil, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
Related
This is my first time on Stack Overflow. I have been trying to make an app that finds the user's current location and outputs the information the doctors close to the user. So far, I can find the current location, however, I am not able to add an annotation for the doctors near the current location.
Here is my code so far:
import UIKit
import MapKit
import CoreLocation
class ThirdViewController: UIViewController, CLLocationManagerDelegate {
#IBOutlet weak var map: MKMapView!
let manager = CLLocationManager()
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
let location = locations[0]
let span:MKCoordinateSpan = MKCoordinateSpanMake(0.01, 0.01)
let myLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)
let region:MKCoordinateRegion = MKCoordinateRegionMake(myLocation, span)
map.setRegion(region, animated: true)
self.map.showsUserLocation = true
}
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestWhenInUseAuthorization()
manager.startUpdatingLocation()
let request = MKLocalSearchRequest()
request.naturalLanguageQuery = "doctor"
request.region = map.region
let localSearch:MKLocalSearch = MKLocalSearch(request: request)
localSearch.start(completionHandler: {(result, error) in
for placemark in (result?.mapItems)! {
if(error == nil) {
let annotation = MKPointAnnotation()
annotation.coordinate = CLLocationCoordinate2DMake(placemark.placemark.coordinate.latitude, placemark.placemark.coordinate.longitude)
annotation.title = placemark.placemark.name
annotation.subtitle = placemark.placemark.title
self.map.addAnnotation(annotation)
}
else
{
print(error ?? 0)
}
}
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
All responses are appreciated and if you have any advice for what I should do next time I ask a question, please leave it down below. Thank you.
Your map view needs a delegate with a mapView(_:viewFor:) implementation. Otherwise, adding an annotation will have no visible effect.
To add an annotation you need to inherit MKMapViewDelegate.
Then add: mapView.delegate = self to your initialization method.
And implement this functions:
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
if !(view.annotation! is MKUserLocation) {
let customPin = view.annotation as! CustomPin //if u wanna use custom pins
configureDetailView(annotationView: view, spotPin: customPin.spotDetailsItem) //configuring view for tap
}
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if annotation is MKUserLocation {
return nil
}
if !(annotation is CustomPin) {
return nil
}
let identifier = "CustomPin"
var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier)
if annotationView == nil {
annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
annotationView?.canShowCallout = true
} else {
annotationView!.annotation = annotation
}
return annotationView
}
configureDetailView method and other information you can find here (its is quite cumbersome)
I relatively new to programming and need help switching between views by tapping a button in a mapView annotated pin.
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
//REF
#IBOutlet weak var mapView: MKMapView!
#IBOutlet weak var bottompnl: UIImageView!
#IBAction func mysticsbtn(sender: AnyObject) {
}
#IBAction func bondibtn(sender: AnyObject) {
}
//MAP
let locationManager = CLLocationManager()
//Annotation
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
let identifier = "beach"
if annotation is Beach {
var annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(identifier)
if annotationView == nil {
annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
annotationView!.canShowCallout = true
let btn = UIButton(type: .DetailDisclosure)
annotationView!.rightCalloutAccessoryView = btn
} else {
annotationView!.annotation = annotation
}
return annotationView
self.performSegueWithIdentifier("mysticssegue", sender: nil)
}
return nil
}
override func viewDidLoad() {
super.viewDidLoad()
let annotations = getMapAnnotations()
// Add mappoints to Map
mapView.addAnnotations(annotations)
mapView.delegate = self
//MAP
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
//MAKES THE DOT
self.mapView.showsUserLocation = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MAP: Location Delegates Methods
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations.last
let centre = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude)
let region = MKCoordinateRegion(center: centre, span: MKCoordinateSpan(latitudeDelta: 3, longitudeDelta: 3))
self.mapView.setRegion(region, animated: true)
self.locationManager.startUpdatingLocation()
}
//TO FIND ERROS
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
print("Erros: " + error.localizedDescription)
}
//MARK:- Annotations
func getMapAnnotations() -> [Beach] {
var annotations:Array = [Beach]()
//load plist file
var beaches: NSArray?
if let path = NSBundle.mainBundle().pathForResource("beaches", ofType: "plist") {
beaches = NSArray(contentsOfFile: path)
}
if let items = beaches {
for item in items {
let lat = item.valueForKey("lat") as! Double
let long = item.valueForKey("long")as! Double
let annotation = Beach(latitude: lat, longitude: long)
annotation.title = item.valueForKey("title") as? String
annotations.append(annotation)
}
}
return annotations
}
//END
}
It looks like you're returning from the function mapView before calling performSegueWithIdentifier.
return annotationView
self.performSegueWithIdentifier("mysticssegue", sender: nil)
Try reversing the order of these two lines. I also noticed that you have some #IBAction methods that have no code in them.
My code:
Please anyone ! How to make this button work !?!??!
What do i put in the #IBAction brackets to have the function i want ?
import UIKit
import MapKit
import CoreLocation
class MapViewController: UIViewController,MKMapViewDelegate, CLLocationManagerDelegate{
#IBOutlet weak var mapView: MKMapView!
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
//==========RegionLocation : =========
// Init the zoom level
let coordinate:CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: 31.30, longitude: 34.45)
let span = MKCoordinateSpanMake(125, 125)
let region = MKCoordinateRegionMake(coordinate, span)
self.mapView.setRegion(region, animated: true)
//====================================\\
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
//Dispose of resources that can be re created.
}
//Mark : Location
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
let location = locations.last
let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.06, longitudeDelta: 0.06))
self.mapView.setRegion(region, animated: true)
self.locationManager.stopUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError)
{
print("Errors: " + error.localizedDescription)
}
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!.canShowCallout = true
pinView!.animatesDrop = true
pinView!.rightCalloutAccessoryView = UIButton(type: UIButtonType.DetailDisclosure) as UIButton
let smallSquare = CGSize(width: 30, height: 30)
let button = UIButton(frame: CGRect(origin: CGPointZero, size: smallSquare))
button.setBackgroundImage(UIImage(named: "Car"), forState: .Normal)
pinView?.leftCalloutAccessoryView = button
}
else
{
pinView!.annotation = annotation
}
return pinView
}
but when i put in the button action segment nothing happens when i press on it ?
Anyone can Guide me on How do i center the mapView onto the user location Blue dot ?
Try this
#IBAction func centerLocationButton(sender: UIButton) {
mapView.setCenterCoordinate(mapView.userLocation.coordinate, animated: true)
}
In order to use MKMapView in correct way just follow the following below code.
// `viewDidLoad` method
#IBOutlet weak var map: MKMapView!
var locationManager: CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
// code for enable location seivices
if (CLLocationManager.locationServicesEnabled())
{
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
}
}
override CLLocationManager.didUpdateLocations see below (part of CLLocationManagerDelegate) to get notified when the location manager retrieves the current location.
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
let location = locations.last as CLLocation
let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
self.map.setRegion(region, animated: true)
}
have a note: If your target is iOS 8, you must include the NSLocationAlwaysUsageDescription key in your Info.plist to get the location services to work.
if you want to set region in a custom way using button action just save lat and long and pass like:
#IBAction func setMap(sender: UIButton) {
let center = CLLocationCoordinate2D(latitude: lat, longitude: long)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
self.map.setRegion(region, animated: true)
}
here is Google map guidelines. and useful tutorial
I can see what you need is to have a button to center the mapView to your current location. It is exactly same as vaibhab's answer with little modifications.
Just create to button and link the action to the viewcontroller class then copy the same code in the IBAction of the button.
#IBAction func updateCurrentLocation(_ sender: AnyObject) {
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
} else {
// Alert to enable location services on iphone first
}
}
Plus you can just add a small line of code to show the blue indicator of the location of the user. In the func locationManager.
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [AnyObject]) {
self.mapView.showsUserLocation = true
}
Make sure when you are using the simulator just add a custom location from the simulators menu. Debug ---> location ----> Custom
If using a real mobile just make sure that the location services is on in the Settings---> General----> Privacy
I am using regionDidChangeAnimated for my mapView. I want to detect when user zoom's or drag's a map. Drag is being detected, but I can't seem to detect when user zoom's the map. I tried to use:
func mapView(mapView: MKMapView, regionWillChangeAnimated animated: Bool) {
print("region will change")
}
But when I zoom my map it does not work.
Full code:
var locationManager: CLLocationManager = CLLocationManager()
var startLocation: CLLocation!
#IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
//get current location
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
self.mapView.showsUserLocation = true
startLocation = nil
let mapDragRecognizer = UIPanGestureRecognizer(target: self, action: "didDragMap:")
mapDragRecognizer.delegate = self
self.mapView.addGestureRecognizer(mapDragRecognizer)
self.mapView.pitchEnabled = true
self.mapView.showsBuildings = true
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [CLLocation]) {
let location = locations.last
let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05))
mapView.setRegion(region, animated: false)
let currentLocX = String(format: "%.4f", location!.coordinate.latitude)
let currentLocY = String(format: "%.4f", location!.coordinate.longitude)
self.locationManager.stopUpdatingLocation()
}
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
print("Errors: " + error.localizedDescription)
}
func didDragMap(gestureRecognizer: UIGestureRecognizer) {
print("Drag")
}
func mapView(mapView: MKMapView, regionWillChangeAnimated animated: Bool) {
print("Zoom")
}
I have solved it. In the override func viewDidLoad() need to add self.mapView.delegate = self
And add functions for determine zoom's on the map:
private var mapChangedFromUserInteraction = false
private func mapViewRegionDidChangeFromUserInteraction() -> Bool {
let view = self.mapView.subviews[0]
if let gestureRecognizers = view.gestureRecognizers {
for recognizer in gestureRecognizers {
if( recognizer.state == UIGestureRecognizer.State.began || recognizer.state == UIGestureRecognizer.State.ended )) {
return true
}
}
}
return false
}
func mapView(_ mapView: MKMapView, regionWillChangeAnimated animated: Bool) {
mapChangedFromUserInteraction = mapViewRegionDidChangeFromUserInteraction()
}
func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
if (mapChangedFromUserInteraction) {
print("ZOOM finished")
}
}
Im trying to create an app with two user types...one sends a location and the other user type (on a different device) searches an area and finds the closest user.
I have been on parse's website and stack overflow...they all seem to start in the middle. I would like to have somebody explain the first steps
Heres my code
import UIKit
import MapKit
import CoreLocation
import Parse
class ViewController: UIViewController, MKMapViewDelegate,
CLLocationManagerDelegate, UISearchBarDelegate,
UIGestureRecognizerDelegate
{
#IBOutlet weak var photographer1: UIButton!
#IBOutlet weak var buyer1: UIButton!
#IBOutlet weak var mapView: MKMapView!
#IBOutlet weak var searchBar: UISearchBar!
let locationManager = CLLocationManager()
var searchController:UISearchController!
var annotation:MKAnnotation!
var localSearchRequest:MKLocalSearchRequest!
var localSearch:MKLocalSearch!
var localSearchResponse:MKLocalSearchResponse!
var error:NSError!
var pointAnnotation:MKPointAnnotation!
var pinAnnotationView:MKPinAnnotationView!
override func viewDidLoad()
{
super.viewDidLoad()
self.locationManager.delegate = self
self.mapView.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
self.mapView.showsUserLocation = true
}
// to run the animation this sec of code checks if the region was changed
var mapChangedFromUserInteraction = false
func mapViewRegionDidChangeFromUserInteraction() -> Bool {
let view = self.mapView.subviews[0]
// 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) {
hobo()
//
buyer1.center = CGPointMake(188.0, 513.0)
photographer1.center = CGPointMake(188.0, 581.0)
}
}
// your boy
// MARK: - Location Delegate Methods
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
let location = locations.last
let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
self.mapView.setRegion(region, animated: true)
self.locationManager.stopUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError)
{
print("Error: " + error.localizedDescription)
}
func searchBarSearchButtonClicked(searchBar: UISearchBar){
//1
searchBar.resignFirstResponder()
dismissViewControllerAnimated(true, completion: nil)
if self.mapView.annotations.count != 0{
annotation = self.mapView.annotations[0]
self.mapView.removeAnnotation(annotation)
}
//2
localSearchRequest = MKLocalSearchRequest()
localSearchRequest.naturalLanguageQuery = searchBar.text
localSearch = MKLocalSearch(request: localSearchRequest)
localSearch.startWithCompletionHandler { (localSearchResponse, error) -> Void in
if localSearchResponse == nil{
let alertController = UIAlertController(title: nil, message: "Place Not Found", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alertController, animated: true, completion: nil)
return
}
//3
self.pointAnnotation = MKPointAnnotation()
self.pointAnnotation.title = searchBar.text
self.pointAnnotation.coordinate = CLLocationCoordinate2D(latitude: localSearchResponse!.boundingRegion.center.latitude, longitude: localSearchResponse!.boundingRegion.center.longitude)
self.pinAnnotationView = MKPinAnnotationView(annotation: self.pointAnnotation, reuseIdentifier: nil)
self.mapView.centerCoordinate = self.pointAnnotation.coordinate
self.mapView.addAnnotation(self.pinAnnotationView.annotation!)
}
}
func hobo(){
print("testing")
}
#IBAction func showSearchBar(sender: AnyObject) {
searchController = UISearchController(searchResultsController: nil)
searchController.hidesNavigationBarDuringPresentation = false
self.searchController.searchBar.delegate = self
presentViewController(searchController, animated: true, completion: nil)
}
#IBAction func locateMe(sender: AnyObject) {
self.mapView.showsUserLocation = true
self.locationManager.startUpdatingLocation()
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestWhenInUseAuthorization()
buyer1.center = CGPointMake(188.0, 581.0)
photographer1.center = CGPointMake(188.0, 513.0)
}
#IBAction func photographer(sender: AnyObject) {
}
#IBAction func buyer(sender: AnyObject) {
}
}