How to Get User Location on a Map - Swift

  Рет қаралды 62,712

Sean Allen

Sean Allen

Күн бұрын

Head to squarespace.com/seanallen to save 10% off your first purchase of a website or domain using code SEANALLEN.
In today's video I show you how to show a user's location on a map in SwiftUI using MapKit and CoreLocation. We also discuss how to ask for location permission and handle the various permission states.
This tutorial was created in Xcode 13 and iOS 15 (betas).
*** Yes, I'm aware of the new LocationButton released with iOS 15. Because that requires iOS 15, that will be a separate video in the future.
If you like my teaching or presentation style, I've started creating my own courses:
seanallen.teachable.com/
CLLocationManager Documentation:
developer.apple.com/documenta...
Twitter:
/ seanallen_dev
Link to my book - How I Became an iOS Developer:
gumroad.com/l/sean-allen-origin
Timestamps
0:00 - What You’ll Learn
0:11 - Display a Map
3:13 - MKCoordinateSpan
3:58 - Begin User Location Process
5:10 - ViewModel & Architecture Discussion
6:28 - CLLocationManager Setup
8:57 - Check App’s Authorization & Request Permission
12:30 - Property List Setup for Location Permissions
13:42 - CLLocationManagerDelegate Setup
17:01 - Where to call checkIfLocationServiceIsEnabled()
18:10 - Set Location of Simulator
18:28 - Test Location Permission
19:09 - Center Map on User Location
23:17 - Light Refactor & Cleanup
Hired.com:
hired.com/x/1n01g
Check out my podcast, iOS Dev Discussions:
itunes.apple.com/us/podcast/i...
Book and learning recommendations that help out the channel if you decide to purchase (Affiliate Links):
Paul Hudson's Hacking With Swift:
gumroad.com/a/762098803
Donny Wals - Combine:
gumroad.com/a/909014131
Mark Moeyken’s SwiftUI Books:
www.bigmountainstudio.com/swiftui-views-book/fzc51
Objc.io Books (Thinking in SwiftUI & Advanced Swift):
gumroad.com/a/656585843
Ray Wenderlich Books:
store.raywenderlich.com/a/208...
Links to my iOS Dev Setup & iOS Dev Book Recommendations
www.amazon.com/shop/seanallen
#swift #softwaredeveloper #iosdeveloper

Пікірлер: 120
@seanallen
@seanallen 2 жыл бұрын
If you enjoy my teaching/presentation style I have my own iOS Development courses at seanallen.teachable.com. You can watch the first ~10% of each one for free to get a feel for them.
@KimbrellBrad
@KimbrellBrad 2 жыл бұрын
I am in your course and have learned a ton about MapKit and CoreLocation (plus lots of other functionality!) Can't say enough about how well your teaching style fits me. I like to say that Sean "speaks to me!"
@seanallen
@seanallen 2 жыл бұрын
Happy to hear it, Brad!
@sharanraj3306
@sharanraj3306 2 жыл бұрын
A very informative video of Maps in SwiftUI. Glad they added maps support in SwiftUI, previously we had to work with bridging UIViewCpntroller for Maps which was messy. Thoroughly enjoyed it. Keep up the good work, really looking forward for more such videos
@seanallen
@seanallen 2 жыл бұрын
Glad you enjoyed it, Sharan!
@bbulliard
@bbulliard 2 жыл бұрын
World class video. You are an artful, gifted teacher. I love seeing information this well explained. Thank you for putting this together…
@kevinhawthorne5257
@kevinhawthorne5257 2 жыл бұрын
Thank You for all of your videos that you did. I am enjoying all of them
@seanallen
@seanallen 2 жыл бұрын
Glad you are enjoying the channel, Kevin 😀
@jonazthepro4415
@jonazthepro4415 10 ай бұрын
Pretty late, but I wanna say this is a GREAT tutorial. You address everything indepth but not too indepth that it gets boring, you don't dwell over unnecessary parts and most importantly you explain the use of each line. You saved my ass for my school project. Cheers.
@seanallen
@seanallen 10 ай бұрын
I appreciate this. That's exactly the style I go for. I don't want to overwhelm the viewer with way too much information, but give just enough to understand what's going on. Glad I could help!
@DaveJacobseniOS
@DaveJacobseniOS 2 жыл бұрын
Thanks for the quality vid! I was needing to do this exact thing so this helped me a bunch.
@zb1123
@zb1123 2 жыл бұрын
Another great video, very informative (as always)! Cheers!
@seanallen
@seanallen 2 жыл бұрын
Thanks, Z B. Glad you enjoyed it!
@ivanbartolelli
@ivanbartolelli 2 жыл бұрын
Amazing video, Sean. You're helping me with my Engineering Final Project. A lot of doubts were resolved. Thanks a lot!
@ggarnik
@ggarnik Жыл бұрын
Thank you. Super helpful tutorial!
@AdailtonSilvaSP
@AdailtonSilvaSP 11 ай бұрын
Thank you for this video. it was very helpful!
@vamsi3877
@vamsi3877 2 жыл бұрын
Helpful Thanks Sean 👏
@antonshvetsov1985
@antonshvetsov1985 2 жыл бұрын
Super lesson! Make a video on how to click on button and get complex results (json, etc)
@chrispy104k
@chrispy104k 2 жыл бұрын
Great content as always Sean. 👍
@spectator5144
@spectator5144 Ай бұрын
PERFECT video. thank you and congratulations.
@seanallen
@seanallen 29 күн бұрын
Glad you liked it!
@andrewdonnelly4406
@andrewdonnelly4406 Жыл бұрын
Great stuff, I was trying to figure out how to change the accent colour of the users location. Thanks !!
@AZMerf
@AZMerf 2 жыл бұрын
Great video and content. Thanks Sean.
@seanallen
@seanallen 2 жыл бұрын
Glad you enjoyed it, Merrill.
@judy8821
@judy8821 2 жыл бұрын
Thanks! Great explanation as usual! This actually worked fine with iOS 14
@seanallen
@seanallen 2 жыл бұрын
Glad you enjoyed it, Judy!
@leonardbrenk1409
@leonardbrenk1409 17 күн бұрын
Great video, thanks!
@seanallen
@seanallen 17 күн бұрын
Glad you liked it!
@christostsangaris4785
@christostsangaris4785 Жыл бұрын
Again, superb tutorial by Sean!! I get this error though: "This method can cause UI unresponsiveness if invoked on the main thread. Instead, consider waiting for the `-locationManagerDidChangeAuthorization:` callback and checking `authorizationStatus` first." Any idea how to overcome it?
@morganwolff218
@morganwolff218 Жыл бұрын
I have the same error and idk how to fix this, i can't see my location because of that
@garytimeless7251
@garytimeless7251 Жыл бұрын
this is very useful, i want to build an running app, so this is a good start. You heped me a lot, now i want to figure out how to track movement :D
@seanallen
@seanallen Жыл бұрын
Glad I could help, Gary!
@Connor-pj2tg
@Connor-pj2tg 2 жыл бұрын
This looks really good Sean, thank you. Do you think you could tackle this issue I'm having, specifically the segment control on Instagram/Tiktok and Twitters profile pages. No matter what I do I can't make it dynamic. Is it possible, would love to see you do this, as I don't think any other iOS channel has tackled it yet!
@jonathanbauer6711
@jonathanbauer6711 2 жыл бұрын
Thank you for the great explenation. Is there a possibility to do directions similar as in the native "Maps" app within the app itself? Or do i have to source that out to the native "Maps" app? Thanks in advance
@relax_music668
@relax_music668 2 жыл бұрын
Very good,Thanks.
@sk4tec
@sk4tec Жыл бұрын
Hey Sean, great video... reminds me I need to get on with Dub Dub Grub course!
@nickapeed
@nickapeed Жыл бұрын
Thanks!
@seanallen
@seanallen Жыл бұрын
I appreciate the generous support, Nick!
@edwardhasted3849
@edwardhasted3849 11 ай бұрын
Sean - having looked around this is by far the most concise, simplest and well structured posting on this topic and thank you. Whereas the new MapKit is a delight CoreLocation remains Byzantine. Without being too big a pedant would it be possible to rework this video for iOS 17.0, or do an addendum, as there are places that now give purple or yellow warnings. Map(coordinateRegion: $viewModel.region, showsUserLocation: true) has even been deprecated...
@tariqAlmazyad
@tariqAlmazyad 2 жыл бұрын
another great video by great content creator .
@seanallen
@seanallen 2 жыл бұрын
Thanks Tariq!
@bikewithme224
@bikewithme224 Жыл бұрын
You are the best!!
@seanallen
@seanallen Жыл бұрын
Thanks for the kind words.
@ChristianHancke
@ChristianHancke 2 жыл бұрын
Thank you!!!!
@nigelgee3576
@nigelgee3576 2 жыл бұрын
Great video. I just want to ask one question. Why did you have checkLocationAuthorization() when you can do the switch in locationManagerDidChangeAuthorization(_ manager: CLLocationManager) and switch on manager. You said this is called when CLLocationManager is intallized.
@mariamsargsyan608
@mariamsargsyan608 2 жыл бұрын
Thanks, super!!!
@alexfactory5426
@alexfactory5426 2 жыл бұрын
Hey, thanks so much for this tutorial! I‘ve got a little problem trying to force-unwrap: „region = ...( center: locationManager.location!.coordinate...), always displays an error because of the non optional type/ nil. Do you know how I could properly unwrap it? You left it out in your video and I didn‘t manage to find an answer..
@minilord11
@minilord11 2 жыл бұрын
with an iPhone it works, have the same problem with the simulator, don't know why
@williamsouef6156
@williamsouef6156 Жыл бұрын
Hey Alex, I came with this solution try to unwrap like that region = MKCoordinateRegion(center: locationManager.location?.coordinate ?? CLLocationCoordinate2D(latitude: 43.70313, longitude: 7.26608) Letting know the optional a default location if we don't achieved to pick up the current location of the user. Hope this will help
@coffeetime5385
@coffeetime5385 Жыл бұрын
Is it possible to get the current elevation based on the location aswell?
@-Timmy0604
@-Timmy0604 Жыл бұрын
Is there a way to add like an image the the users location with a click of a button?
@aldanahalqbbani
@aldanahalqbbani Жыл бұрын
I love it !!!!!
@seanallen
@seanallen Жыл бұрын
Glad you liked it!
@SkillTrailMalefiahs
@SkillTrailMalefiahs Жыл бұрын
Gracias a ti aprendí el delegate!
@seanallen
@seanallen Жыл бұрын
😀👍
@tomfarrell7307
@tomfarrell7307 2 жыл бұрын
Do IOS developers need to register with Apple and receive an API key to use apple maps in their applications?
@newFort4
@newFort4 2 жыл бұрын
Why assigning the delegate after object is constructed invokes the delegate method?
@Olden2610
@Olden2610 Жыл бұрын
Few comments for better coding approach: 1.) `checkIsLocationServicesIsEnabled` should be static (or class if you plan to, lets say, deploy it as library), and not internal 2.) `checkIsLocationServicesIsEnabled` should return Bool, and not create/change something rom inside. For what you've written in this methods - it's looks more like `initializeLocationManagerIfPossible` which is throws error (or also returns Bool, but error would be much better option for information purposes)
@tarunreddy3599
@tarunreddy3599 2 жыл бұрын
For some reason it wont let me force unwrap the user location to center the screen on it.. any thoughts?
@rgb5026
@rgb5026 Жыл бұрын
.nice vid bud with but....problem: This method can cause UI unresponsiveness if invoked on the main thread. Instead, consider waiting for the `-locationManagerDidChangeAuthorization:` callback and checking `authorizationStatus` first." Any idea how to overcome it?
@gekoskipatric
@gekoskipatric 2 жыл бұрын
why was it necessary to extend NSObject? Couldn't we have just conformed to the protocols?
@tarun_reddy
@tarun_reddy 2 жыл бұрын
I keep getting this error: Error Domain = kCLErrorDomain Code = 1 “(null)” . Any Idea on why that may be happening? Thank you great video!
@supportderoue8035
@supportderoue8035 Жыл бұрын
I have a problem at around 17:17, when you enter viewModel .... I dont have access to this variable ! Do you know how ? Thnak's for the help !, forget, I found my error
@jemmytech5474
@jemmytech5474 12 күн бұрын
I don't see the red circle marker on the current user location?
@alondob
@alondob 2 жыл бұрын
Great video! I’m inspired to update my map code now. What is the pro/con of using enum vs. struct for MapDetail?
@seanallen
@seanallen 2 жыл бұрын
It's a very minor detail, but when you use a struct for that sort of thing, it is possible to initialize and empty struct (like MapDetails()) and that shows up in the auto-complete. It's really not a huge deal and more of a small "quality of life" improvement.
@iOSDev05
@iOSDev05 Жыл бұрын
How to do it with MVVM?
@Moch117
@Moch117 4 ай бұрын
Thanks for this Sean! One note though : Your view model is creating the CLLocationManager here. This breaks the concept of dependency injection right?
@TheStuze
@TheStuze Жыл бұрын
Dont know if you still reply, but when You use NSObject, why did you ? and do you have a video explaining it if so.
@emperor_yt
@emperor_yt 3 ай бұрын
could you provide a link to the source code :)
@fsdolphin
@fsdolphin Жыл бұрын
Great tutorial! Thanks. Two things I had to do to make it work in iOS 14.1+. 1. I had to wrap the `if CLLocationManager.locationServicesEnabled()` in a `DispatchQueue.global().async {if CLLocationManager.locationServicesEnabled()}` 2. The other thing I had to do is initialize `CLLocationManger()` right at the begging of the class instead of inside `if CLLocationManager.locationServicesEnabled()`.
@ArchAid1
@ArchAid1 2 жыл бұрын
Hi Sean :) Love this! One thing that I've never been able to figure out though, is how to place a pin on a random location on the map, and then get those coordinates. Like when you move the needle in the Uber app to set a different location. Is this something you could show/explain? Fabulous content 🙏
@seanallen
@seanallen 2 жыл бұрын
I believe you are looking for reverse-geolocation. I did a video on that topic a couple years ago here - kzfaq.info/get/bejne/aN2oeJuT3smWdoU.html
@ArchAid1
@ArchAid1 2 жыл бұрын
@@seanallen Awesome mate! You're a star 🌟
@ArchAid1
@ArchAid1 2 жыл бұрын
@@seanallen umm.. I watched the previous video, and for someone who never really got into UIKit it was quite hard 😅 Granted, there is a lot of stuff out there on SwiftUI/UIKit interoperability, but your teaching style is better you know 😁😉 So, if you ever decide to do a "How to get data out of UIKit and into SwiftUI" Then this would be a great topic to do said demonstration (getting the location out of the map and into my SwiftUI view). And again, and always, thanks a mill for everything you're doing for the learning community 🙏🙏
@seanallen
@seanallen 2 жыл бұрын
Try this one for UIKit/SwiftUI interoperability. kzfaq.info/get/bejne/jJObhrabzZe4Z2g.html
@charlesmagno28
@charlesmagno28 5 ай бұрын
Hi Sean, do you have any recommended templates to start with for a Ticketing system? will fetch data from a site, thanks!
@seanallen
@seanallen 4 ай бұрын
Unfortunately not. I've never built a ticketing system before so I have no experience here.
@whipit2404
@whipit2404 2 жыл бұрын
Why don't you use storyboard?
@user-zi8fs5wd5r
@user-zi8fs5wd5r 2 жыл бұрын
Hi Sean Allen I'm a student who's been listening intently to your lectures. may i know the xcode theme? Also, I'm curious about the font and font size! Also, I'm curious about the keyboard and the Mac product you're using. Sorry, I have a lot of questions. p.s It's Google Translate, so the sentences may be a bit awkward.
@seanallen
@seanallen 2 жыл бұрын
The Xcode theme I use is called "Midnight". You can go to Xcode -> Preferences -> Themes to select it.
@ssadel
@ssadel 2 жыл бұрын
How do I grab the user latitude and longitude as 2 separate doubles after this to use in a new tabview? When I force unwrap locationManager!.location!.coordinate.latitude in another function in my viewmodel, it causes an error because the value is nil.
@Moch117
@Moch117 2 ай бұрын
I think the problem is the location is never fetched. Hes hard-coding some location in. Theres no method here thats requesting any location
@LoriWolfcat
@LoriWolfcat 2 жыл бұрын
So, what if you Just want the user’s authorization of location? Like Facebook, Instagram, and chat apps have that, so what would you put? Also, if you get the authorization, does that come with the weather conditions too? I would wanna see if I can make an app that just uses the location and weather. There’s different monsters for different weather, so if it’s hot or cold weather, it would have more water monsters in the cold and fire monsters in the heat.
@LTNKidd
@LTNKidd 2 жыл бұрын
I'm learning something similar. You''ll probably want to pull locations from JSON and display as Pin on map. Might be best to pull this from a JSON on a server and display as pin on map. I've got the JSON pulling into a list for a dashboard and am trying to now display these as pins. Not all that dissimilar from Yelp. Happy to learn if you've got a video recommendation Sean!
@blakefoss8819
@blakefoss8819 2 жыл бұрын
Hi Sean, thanks for taking the time to put this together, I have found your videos useful in a project I am working on. I'm getting an error that I can figure out. When ever I run the app I get the following error, "Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value" it relates to the code in the ContentViewModel file "center: locationManager.location!.coordinate," I'm not 100% sure what I am missing, I have checked the code carefully against what I see in the video and it is 1:1. Thank you for your assistance with this.
@zazoobah
@zazoobah 2 жыл бұрын
case .authorizedAlways, .authorizedWhenInUse: region = MKCoordinateRegion(center: MapDetails.startLocation, span: MapDetails.defaultSpan)
@steveburton5825
@steveburton5825 2 жыл бұрын
@@zazoobah This will just set the location to the default location, not the updated location by the GPS (to his house and not Cupertino in this example).
@zazoobah
@zazoobah 2 жыл бұрын
@@steveburton5825 Yep, the OP noted that a Fatal error occurred - the code I posted overcomes that. Location updates are done through the remainder of the code Sean presents.
@Jump_Jay
@Jump_Jay 2 жыл бұрын
@@zazoobah I tried that and the code still has a fatal error. 😡
@zazoobah
@zazoobah 2 жыл бұрын
@@jackychow868 Fixing the problem was what I posted. What you are doing with the region value is up to you, i.e. you'll need to respond to .regionChanged(region:)
@akashsharkarakashsharkar2350
@akashsharkarakashsharkar2350 Жыл бұрын
nice
@srome0711
@srome0711 Жыл бұрын
How do you properly unwrap that optional in the switch statement? - Looks like I cant use a guard statement within the case?
@rafaelplinio6527
@rafaelplinio6527 Жыл бұрын
guard let locationCoordinate = locationManager.location?.coordinate else { return }
@mauroabrantes5948
@mauroabrantes5948 Жыл бұрын
Hi, awesome video ! Im not receiving the request to give permission to share my location. Anyone else having that problem ? Im running on Iphone 12 pro max with iOS 16.0.3
@josephhansen8122
@josephhansen8122 2 жыл бұрын
I'm stuck on the last part - fixing the $region to $viewModel.region. I'm getting an error that says 'region' is inaccessible due to 'private' protection level
@oscargustafsson5844
@oscargustafsson5844 Жыл бұрын
Have you changed the region variable from "@State private var region = .." to "@Published var region = ..", That and move it right beneath the " final class ContentViewModel"
@oscarmartinez-pc1nj
@oscarmartinez-pc1nj 9 ай бұрын
anyone know what this warning message means 'init(coordinateRegion:interactionModes:showsUserLocation:userTracKingMode:)' was deprecated in IOS 17.0: Use Map Initializers that take a MapContentBuilder instead.
@seanallen
@seanallen 9 ай бұрын
Maps were revamped in iOS 17. I have a new maps video coming out in a couple weeks with the new iOS 17 Map stuff.
@jameswhitaker4357
@jameswhitaker4357 8 ай бұрын
@@seanallen please release it asap bro! I have been pulling out my hair trying to get map stuff integrated on my prototype
@seanallen
@seanallen 8 ай бұрын
Coming next week!
@anishkakkar2603
@anishkakkar2603 Жыл бұрын
hey Sean I'm facing an error can you help me? error is in the "if" line and it says. - "This method can cause UI unresponsiveness if invoked on the main thread. Instead, consider waiting for the `-locationManagerDidChangeAuthorization:` callback and checking `authorizationStatus` first."
@edwardhasted3849
@edwardhasted3849 Жыл бұрын
Very great video. Now for the downer: The folks at Apple in 14/14.1 seem to have changed the way CLLocationManager.locationServicesEnabled() works and gives the error Anish is reporting. The workarounds on Stack seem convoluted. Is there a short, clean Sean solution?
@rafaelplinio6527
@rafaelplinio6527 Жыл бұрын
It was showing a purple warning for me. I put the whole if statement inside a dispatchQueue: DispatchQueue.global().async { if here }
@srome0711
@srome0711 Жыл бұрын
@@edwardhasted3849 Same here
@jemmytech5474
@jemmytech5474 12 күн бұрын
DispatchQueue.global() .async { if CLLocationManager.locationServicesEnabled() { self.locationManager = CLLocationManager() // locationManager?.desiredAccuracy = kCLLocationAccuracyBest self.locationManager!.delegate = self } else { print("Show an alert letting them know this is off") } }
@jackychow868
@jackychow868 2 жыл бұрын
For those who had Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value" it relates to the code in the ContentViewModel file...."" Fix: Restart the simulator and Xcode, run it again (Xcode version 13.4.1 (13F100)) Nothing wrong with the code, most likely the simulator thing.
@pierremartin9064
@pierremartin9064 2 жыл бұрын
The map is always empty.
@dugrut1325
@dugrut1325 2 жыл бұрын
everything worked except the pink location dot
@rafaelplinio6527
@rafaelplinio6527 Жыл бұрын
Same thing for me!
@petaropacic4059
@petaropacic4059 2 жыл бұрын
if anyone has an "force-unwrap" error at "location!.coordinate" change the code to this case.authorizedAlways, .authorizedWhenInUse: if let loc = locationManager.location{ region = MKCoordinateRegion(center: locatitonManager.location!.coordinate, span: yourSpan) } This is called Optional Binding
@alexsmithers866
@alexsmithers866 2 жыл бұрын
Mine didn’t like if let loc. I had to change it to if locationManager.location != nil But then it didn’t ask for permission when I ran it 😕 but it didn’t get a fatal error
@fabiopizzano2101
@fabiopizzano2101 2 жыл бұрын
Thank you!!
SwiftUI Segmented Control Tutorial | iOS 14 | Xcode 12.4
8:50
Sean Allen
Рет қаралды 23 М.
SwiftUI List with Custom Cell & Passing Data
36:27
Sean Allen
Рет қаралды 115 М.
БАБУШКИН КОМПОТ В СОЛО
00:23
⚡️КАН АНДРЕЙ⚡️
Рет қаралды 16 МЛН
Looks realistic #tiktok
00:22
Анастасия Тарасова
Рет қаралды 106 МЛН
КАК ДУМАЕТЕ КТО ВЫЙГРАЕТ😂
00:29
МЯТНАЯ ФАНТА
Рет қаралды 10 МЛН
SwiftUI LocationButton - Get User Location |  iOS 15
18:48
Sean Allen
Рет қаралды 16 М.
Your App Will Get Rejected | New Privacy Rules - 2024
11:26
Sean Allen
Рет қаралды 35 М.
SwiftUI MapKit Basics
12:41
CodeWithChris
Рет қаралды 20 М.
Adding user locations to a map - Bucket List SwiftUI Tutorial 6/12
10:49
Request User Location With SwiftUI
26:13
AppStuff
Рет қаралды 10 М.
My FBI Declassified Story
9:26
Marques Brownlee
Рет қаралды 4,4 МЛН
SwiftData Basics in 15 minutes
15:18
CodeWithChris
Рет қаралды 41 М.
Swift Closures Explained
14:23
Sean Allen
Рет қаралды 61 М.
How to use @Observable Macro in SwiftUI | Bootcamp #76
18:52
Swiftful Thinking
Рет қаралды 5 М.
low battery 🪫
0:10
dednahype
Рет қаралды 728 М.
Сколько реально стоит ПК Величайшего?
0:37
Копия iPhone с WildBerries
1:00
Wylsacom
Рет қаралды 7 МЛН
Ноутбук за 20\40\60 тысяч рублей
42:36
Ремонтяш
Рет қаралды 389 М.