I have been trying to make my own mapView that displays your current location so I went to watch Vea Software's video link found here and I did these steps
Wrote the code:
//
// ViewController.swift
// MapView
//
// Created by HTML SUES ADMIN on 10/5/15.
// Copyright © 2015 HTML SEUS. All rights reserved.
//
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate
{
#IBOutlet weak var mapView: MKMapView!
let locationManager = CLLocationManager()
override func viewDidLoad()
{
super.viewDidLoad()
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.requestAlwaysAuthorization()
self.locationManager.startUpdatingLocation()
self.mapView.showsUserLocation = true
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// 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: 1, longitudeDelta: 1))
self.mapView.setRegion(region, animated: true)
self.locationManager.stopUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
print("Errors: " + error.localizedDescription)
}
}
Realized I made a mistake and added this piece of code under
super.viewDidLoad()
I added,
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.requestAlwaysAuthorization()
Added this under Info.plist (it's a imgur file/no download)
Ran the Xcode project got the map to pull up with the Location notification but didn't show current location. Instead came up with this
Errors: The operation couldn’t be completed. (kCLErrorDomain error 0.)
Errors: The operation couldn’t be completed. (kCLErrorDomain error 0.)
yes 2 of the same, I think because of
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.requestAlwaysAuthorization()
but maybe it's because the location is not in iPhone Simulator so it bugs out.
So 2 things to help me with:
how to find your current location if there is any way?
why does it only work on the first View Controller and not the second one? It is embedded in a navigation controller.
Ok to start off I know this is weird to answer my own question but after further research I have came up with this answer
Errors: The operation couldn’t be completed. (kCLErrorDomain error 0.) = This error occurs if you have Scheme/Edit Scheme/Options/Allow Location Simulation checked but don't have a default location set.
don't have a default location set. - was my problem thanks everyone who helped
Related
I have an app that finds places near the user’s location, however, the app crashes the second time it runs with the exception:
fatal error: unexpectedly found nil while unwrapping an Optional value.
On line:
self.googleMapView.animate(toLocation: coordinates)
I checked and the googleMapView is nil but I don’t understand how it is nil or how it ran the first time. It only starts crashing on subsequent tries if I delete and reinstall the app it works fine on the first try but after that it keeps crashing even if I restart the app. Full code below
import UIKit
import GoogleMaps
import GooglePlacePicker
import MapKit
class MapViewController: UIViewController, CLLocationManagerDelegate {
var currentLongitude: CLLocationDegrees = 0
var currentLatitude: CLLocationDegrees = 0
var locationManager: CLLocationManager!
var placePicker: GMSPlacePickerViewController!
var googleMapView: GMSMapView!
#IBOutlet weak var mapViewContainer: MKMapView!
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.googleMapView = GMSMapView(frame: self.mapViewContainer.frame)
self.googleMapView.animate(toZoom: 18.0)
self.view.addSubview(googleMapView)
}
override func viewDidLoad() {
super.viewDidLoad()
self.locationManager = CLLocationManager()
self.locationManager.delegate = self
self.locationManager.requestAlwaysAuthorization()
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location:CLLocation = locations.last {
self.currentLatitude = location.coordinate.latitude
self.currentLongitude = location.coordinate.longitude
}
else {
print("Location Error")
}
let coordinates = CLLocationCoordinate2DMake(self.currentLatitude, self.currentLongitude)
let marker = GMSMarker(position: coordinates)
marker.title = "I am here"
marker.map = self.googleMapView
self.googleMapView.animate(toLocation: coordinates)
}
private func locationManager(manager: CLLocationManager,
didFailWithError error: Error){
print("An error occurred while tracking location changes : \(error.localizedDescription)")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Crash is pretty self-explanatory:
You are setting your location's delegate in the viewDidLoad but creating the map in the viewDidAppear.
If the location was known by iOS, you will receive the message before viewDidAppear call so in the line : self.googleMapView.animate(toLocation: coordinates), your map is still nil
You can either define your map as optional : var googleMapView: GMSMapView?, or you can wait for your map to be defined to create your location Manager.
After doing some research and asking other question on stack i can not seem to figure out the issue. Yet i have come far.
I am new to Stack so please let me know if i need to provide more information.
The error is appering at
self.mapView.showsUserLocation = true
Saying in the compiler
fatal error: unexpectedly found nil while unwrapping an Option Value
IIDB
if i delete that line the error appears on a another .mapView. line.
When i move the line where the error appear, and put it under:
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
The app opens and everything works fine, except it dont show the location, but i am able to run the app without getting any error.
Thank you for your time.
Here is my codes if someone need it.
import UIKit
import Parse
import CoreLocation
import MapKit
class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
#IBOutlet weak var mapView: MKMapView!
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
self.mapView.showsUserLocation = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// 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: 1, longitudeDelta: 1))
self.mapView.setRegion(region, animated: true)
self.locationManager.stopUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
print("Error:" + error.localizedDescription)
}
}
The only reason why it would be returning a found nil error on a property would be because the property had not yet been instantiated. Given that you're using an IBOutlet, I imagine that you haven't hooked the property to the map view in your storyboard.
See Swift: "mapView.showUserLocation = true" returns "fatal error: unexpectedly found nil while unwrapping an Optional value (lldb) " for more info.
Try to add locationManager.requestLocation() instead of self.mapView.showsUserLocation = true
Check if your info.plist contains 'Privacy - Location Usage Description'
I am very new to stackexchange so please let me know if i need to provide more information.
I tried to install the Corelocation and Mapkit and use them togheter. Every since i followed Vea Software Tutorial i have recived the following error:
Thread 1: EXC_BAD_INSTRUCTION(code=EXC_1386_INVOP,subcode=0x0)
In the compiler it says
fatal error: Unexpectedly found nil while unwrapping an Optional
Value(llDB)
The error is appering right at this line, but when i delete it, it appears at another Mapkit/Location core line. The error:
self.mapView.showsUserLocation = true
EDIT: When i remove the line above, the same error appears on
self.mapView.setRegion(region, animated: true)
I have been searching around for a while on the internet but nothing really helps me out. Thank you for your time.
If you need the whole viewcontroller code. Here it is.
import UIKit
import Parse
import CoreLocation
import MapKit
class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
#IBOutlet weak var mapView: MKMapView!
let locationManager = CLLocationManager()
#IBOutlet var UsernameTextField: UITextField!
#IBOutlet var PasswordTF: UITextField!
#IBOutlet var EmailTF: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
self.mapView.showsUserLocation = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// 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: 1, longitudeDelta: 1))
self.mapView.setRegion(region, animated: true)
self.locationManager.stopUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
print("Error:" + error.localizedDescription)
}
}
This just an hypothesis by I noticed you use
self.mapView.setRegion(region, animated: true)
in the CLLocationManager delegate and start updating before mapView is actually showing (i.e. in viewDidLoad).
Could it be that mapView is trying to update its visual states before being installed in the view hierarchy ?
This following code is supposed to grab where I live and display it on the map. My current location however is always set to Cupertino California, I get how this is related to apple and xcode is supposed to be related to xcode HQ, however I am more inclined to test this in my current location, it is something to do with the simulator or perhaps my code? I am using no simulator as found in debug
class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate
{
#IBOutlet var mapView: MKMapView!
let locationManager = CLLocationManager()
override func viewDidLoad()
{
super.viewDidLoad()
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
self.mapView.showsUserLocation = 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: 1, longitudeDelta: 1))
self.mapView.setRegion(region, animated: true)
self.locationManager.stopUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError)
{
print("Errors: " + error.localizedDescription)
}
}
I don't think you can ask the simulator to use your real location, but you can simulate any location.
In the Debug menu of the simulator chose "Location" at the bottom. You can also do it from Xcode when you app is launched also in the Debug menu chose "Simulate Location".
In Xcode go to Product>Debug>SimulateLocation. There are some presets to choose from. You can also add your own custom GPX file to your project to make it more customizable.
The below code is getting the user current location and creating a mapbox map.
problem is that the mapbox map is being created before the users location is obtain.
How may I slow or sync this process?
Thank you in advance,
import UIKit
import CoreLocation
import MapboxGL
class AViewController: UIViewController, CLLocationManagerDelegate {
var manager:CLLocationManager!
var userLocation:CLLocation = CLLocation(latitude: 25.776243, longitude: -80.136509)
override func viewDidLoad() {
super.viewDidLoad()
println("inside viewdidload")
self.getUserLocation()
}//eom
override func viewDidAppear(animated: Bool) {
println("inside viewdidappear")
self.createMapBoxMap()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*** MapBox Functions ************************************************************************/
/*Create preliminary map */
func createMapBoxMap(){
// set your access token
let mapView = MGLMapView(frame: view.bounds, accessToken: "pk.eyJ1IjoiZGFya2ZhZGVyIiwiYSI6IlplVDhfR3MifQ.pPEz732qS8g0WEScdItakg")
mapView.autoresizingMask = .FlexibleWidth | .FlexibleHeight
// set the map's center coordinate
mapView.setCenterCoordinate(CLLocationCoordinate2D(latitude: self.userLocation.coordinate.latitude, longitude: self.userLocation.coordinate.longitude),
zoomLevel: 13, animated: false)
view.addSubview(mapView)
//showing the user location on map - blue dot
mapView.showsUserLocation = true
}//eom
/*** location Functions ************************************************************************/
/*getting user current location*/
func getUserLocation(){
self.manager = CLLocationManager()
self.manager.delegate = self
self.manager.desiredAccuracy = kCLLocationAccuracyBest
self.manager.requestWhenInUseAuthorization()
self.manager.startUpdatingLocation()
}//eom
/*location manager 'didUpdateLocations' function */
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
self.manager.stopUpdatingLocation() //stop getting user location
println(locations)
self.userLocation = locations[0] as! CLLocation
}//eom
/* errors occurred */
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError) {
println("Error:" + error.localizedDescription)
}//eom
}//eoc
Location manager is running asynchronously (expected behavior), which means that it returns immediately and finishes creating the map as soon as the create map box method is called. However, it doesn't mean that the map has gotten a location yet. I'm thinking that the best way to implement this would be to move self.createMapBoxMap() to inside didUpdateLocations and try that. From my experience, you want the creation of your view to happen in a callback from an asynchronous method like this. You might want to have some type of loading view though, because the user will be confused at first.