How to Get User Location on a Map - Swift

Поделиться
HTML-код
  • Опубликовано: 27 дек 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.

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

    Thanks!

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

      I appreciate the generous support, Nick!

  • @jonazthepro4415
    @jonazthepro4415 Год назад +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  Год назад +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!

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

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

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

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

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

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

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

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

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

      Thanks, Z B. Glad you enjoyed it!

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

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

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

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

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

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

    PERFECT video. thank you and congratulations.

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

      Glad you liked it!

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

      Glad I could help, Gary!

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

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

    Thank you for this video. it was very helpful!

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

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

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

    Great video, thanks!

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

      Glad you liked it!

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  • @srome0711
    @srome0711 2 года назад +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 }

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

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

    Thank you. Super helpful tutorial!

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

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

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

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

    Great video and content. Thanks Sean.

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

      Glad you enjoyed it, Merrill.

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

    You are the best!!

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

      Thanks for the kind words.

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

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

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

    Great content as always Sean. 👍

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

    Helpful Thanks Sean 👏

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

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

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

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

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

    another great video by great content creator .

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

    could you provide a link to the source code :)

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

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

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

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

      Glad you enjoyed it, Judy!

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

    Gracias a ti aprendí el delegate!

  • @anishkakkar2603
    @anishkakkar2603 2 года назад +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 2 года назад +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 5 месяцев назад

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

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

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

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

    How to do it with MVVM?

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

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

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

    I love it !!!!!

  • @ssadel
    @ssadel 3 года назад +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 7 месяцев назад

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

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

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

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

    Why don't you use storyboard?

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

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

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

    Dont know if you still reply, but when You use NSObject, why did you ? and do you have a video explaining it if so.

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

  • @김승원-w3q
    @김승원-w3q 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.

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

    Very good,Thanks.

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

    Thank you!!!!

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

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

      Thank you!!

  • @oscarmartinez-pc1nj
    @oscarmartinez-pc1nj Год назад

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

      Coming next week!

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

    Thanks, super!!!

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

    The map is always empty.

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

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

    everything worked except the pink location dot

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

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

    nice