How to Get User Location on a Map - Swift

Поделиться
HTML-код
  • Опубликовано: 4 сен 2024

Комментарии • 120

  • @seanallen
    @seanallen  3 года назад +8

    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 3 года назад +7

    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  3 года назад +1

      Happy to hear it, Brad!

  • @christostsangaris4785
    @christostsangaris4785 Год назад +9

    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 Год назад +2

      I have the same error and idk how to fix this, i can't see my location because of that

  • @antonshvetsov1985
    @antonshvetsov1985 3 года назад +3

    Super lesson! Make a video on how to click on button and get complex results (json, etc)

  • @jonazthepro4415
    @jonazthepro4415 11 месяцев назад +1

    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  11 месяцев назад +1

      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!

  • @alexfactory5426
    @alexfactory5426 3 года назад +15

    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 года назад +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

  • @edwardhasted3849
    @edwardhasted3849 Год назад +1

    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...

  • @spectator5144
    @spectator5144 2 месяца назад +1

    PERFECT video. thank you and congratulations.

    • @seanallen
      @seanallen  2 месяца назад

      Glad you liked it!

  • @kevinhawthorne5257
    @kevinhawthorne5257 3 года назад +3

    Thank You for all of your videos that you did. I am enjoying all of them

    • @seanallen
      @seanallen  3 года назад +1

      Glad you are enjoying the channel, Kevin 😀

  • @sharanraj3306
    @sharanraj3306 3 года назад +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  3 года назад +1

      Glad you enjoyed it, Sharan!

  • @rgb5026
    @rgb5026 Год назад +2

    .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?

  • @andrewdonnelly4406
    @andrewdonnelly4406 Год назад

    Great stuff, I was trying to figure out how to change the accent colour of the users location. Thanks !!

  • @garytimeless7251
    @garytimeless7251 Год назад +1

    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!

  • @zb1123
    @zb1123 3 года назад +4

    Another great video, very informative (as always)! Cheers!

    • @seanallen
      @seanallen  3 года назад +1

      Thanks, Z B. Glad you enjoyed it!

  • @Moch117
    @Moch117 5 месяцев назад

    Thanks for this Sean!
    One note though : Your view model is creating the CLLocationManager here. This breaks the concept of dependency injection right?

  • @leonardbrenk1409
    @leonardbrenk1409 Месяц назад +1

    Great video, thanks!

  • @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)

  • @blakefoss8819
    @blakefoss8819 3 года назад +5

    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 года назад +1

      case .authorizedAlways, .authorizedWhenInUse:
      region = MKCoordinateRegion(center: MapDetails.startLocation, span: MapDetails.defaultSpan)

    • @steveburton5825
      @steveburton5825 2 года назад +1

      @@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:)

  • @tarun_reddy
    @tarun_reddy 2 года назад +1

    I keep getting this error: Error Domain = kCLErrorDomain Code = 1 “(null)” . Any Idea on why that may be happening? Thank you great video!

  • @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…

  • @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()`.

  • @tarunreddy3599
    @tarunreddy3599 2 года назад +2

    For some reason it wont let me force unwrap the user location to center the screen on it.. any thoughts?

  • @DaveJacobseniOS
    @DaveJacobseniOS 2 года назад

    Thanks for the quality vid! I was needing to do this exact thing so this helped me a bunch.

  • @petaropacic4059
    @petaropacic4059 3 года назад +3

    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!!

  • @srome0711
    @srome0711 Год назад +1

    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 }

  • @ivanbartolelli
    @ivanbartolelli 2 года назад

    Amazing video, Sean. You're helping me with my Engineering Final Project. A lot of doubts were resolved. Thanks a lot!

  • @AdailtonSilvaSP
    @AdailtonSilvaSP Год назад

    Thank you for this video. it was very helpful!

  • @bikewithme224
    @bikewithme224 Год назад +1

    You are the best!!

    • @seanallen
      @seanallen  Год назад

      Thanks for the kind words.

  • @Connor-pj2tg
    @Connor-pj2tg 3 года назад

    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!

  • @nickapeed
    @nickapeed Год назад +1

    Thanks!

    • @seanallen
      @seanallen  Год назад +1

      I appreciate the generous support, Nick!

  • @ggarnik
    @ggarnik Год назад

    Thank you. Super helpful tutorial!

  • @judy8821
    @judy8821 3 года назад

    Thanks! Great explanation as usual! This actually worked fine with iOS 14

    • @seanallen
      @seanallen  3 года назад

      Glad you enjoyed it, Judy!

  • @newFort4
    @newFort4 2 года назад +1

    Why assigning the delegate after object is constructed invokes the delegate method?

  • @jemmytech5474
    @jemmytech5474 Месяц назад

    I don't see the red circle marker on the current user location?

  • @nigelgee3576
    @nigelgee3576 3 года назад

    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.

  • @chrispy104k
    @chrispy104k 3 года назад +1

    Great content as always Sean. 👍

  • @-Timmy0604
    @-Timmy0604 Год назад

    Is there a way to add like an image the the users location with a click of a button?

  • @sk4tec
    @sk4tec 2 года назад

    Hey Sean, great video... reminds me I need to get on with Dub Dub Grub course!

  • @vamsi3877
    @vamsi3877 3 года назад +1

    Helpful Thanks Sean 👏

  • @ArchAid1
    @ArchAid1 3 года назад +1

    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  3 года назад +2

      I believe you are looking for reverse-geolocation. I did a video on that topic a couple years ago here - ruclips.net/video/2wxE8byc2FQ/видео.html

    • @ArchAid1
      @ArchAid1 3 года назад +1

      @@seanallen Awesome mate! You're a star 🌟

    • @ArchAid1
      @ArchAid1 3 года назад

      @@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  3 года назад

      Try this one for UIKit/SwiftUI interoperability. ruclips.net/video/V-kSSjh1T74/видео.html

  • @AZMerf
    @AZMerf 2 года назад +1

    Great video and content. Thanks Sean.

    • @seanallen
      @seanallen  2 года назад

      Glad you enjoyed it, Merrill.

  • @charlesmagno28
    @charlesmagno28 6 месяцев назад

    Hi Sean, do you have any recommended templates to start with for a Ticketing system? will fetch data from a site, thanks!

    • @seanallen
      @seanallen  6 месяцев назад

      Unfortunately not. I've never built a ticketing system before so I have no experience here.

  • @josephhansen8122
    @josephhansen8122 2 года назад +1

    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 2 года назад

      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"

  • @jonathanbauer6711
    @jonathanbauer6711 3 года назад

    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

  • @anishkakkar2603
    @anishkakkar2603 Год назад +2

    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 Год назад +3

      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 Месяц назад

      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")
      }
      }

  • @tariqAlmazyad
    @tariqAlmazyad 3 года назад +1

    another great video by great content creator .

  • @coffeetime5385
    @coffeetime5385 Год назад

    Is it possible to get the current elevation based on the location aswell?

  • @SkillTrailMalefiahs
    @SkillTrailMalefiahs Год назад +1

    Gracias a ti aprendí el delegate!

  • @ssadel
    @ssadel 2 года назад +1

    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 3 месяца назад

      I think the problem is the location is never fetched. Hes hard-coding some location in. Theres no method here thats requesting any location

  • @supportderoue8035
    @supportderoue8035 2 года назад

    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

  • @alondob
    @alondob 3 года назад

    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  3 года назад +1

      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.

  • @gekoskipatric
    @gekoskipatric 2 года назад

    why was it necessary to extend NSObject? Couldn't we have just conformed to the protocols?

  • @emperor_yt
    @emperor_yt 4 месяца назад

    could you provide a link to the source code :)

  • @user-zi8fs5wd5r
    @user-zi8fs5wd5r 3 года назад

    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  3 года назад

      The Xcode theme I use is called "Midnight". You can go to Xcode -> Preferences -> Themes to select it.

  • @tomfarrell7307
    @tomfarrell7307 3 года назад

    Do IOS developers need to register with Apple and receive an API key to use apple maps in their applications?

  • @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.

  • @relax_music668
    @relax_music668 2 года назад

    Very good,Thanks.

  • @aldanahalqbbani
    @aldanahalqbbani Год назад +1

    I love it !!!!!

  • @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.

  • @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

  • @ChristianHancke
    @ChristianHancke 2 года назад

    Thank you!!!!

  • @mariamsargsyan608
    @mariamsargsyan608 2 года назад

    Thanks, super!!!

  • @oscarmartinez-pc1nj
    @oscarmartinez-pc1nj 10 месяцев назад

    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  10 месяцев назад +2

      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 10 месяцев назад +1

      @@seanallen please release it asap bro! I have been pulling out my hair trying to get map stuff integrated on my prototype

    • @seanallen
      @seanallen  9 месяцев назад +1

      Coming next week!

  • @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!

  • @iOSDev05
    @iOSDev05 Год назад

    How to do it with MVVM?

  • @whipit2404
    @whipit2404 2 года назад

    Why don't you use storyboard?

  • @akashsharkarakashsharkar2350
    @akashsharkarakashsharkar2350 2 года назад

    nice

  • @dugrut1325
    @dugrut1325 2 года назад

    everything worked except the pink location dot

  • @pierremartin9064
    @pierremartin9064 2 года назад

    The map is always empty.