草庐IT

swift - 尝试在不提示位置授权的情况下启动 MapKit 位置更新

coder 2023-09-10 原文

在我的应用程序中,我使用 MKMapKitMKUserTrackingBarButtonItem 来定位点击的用户。当我点击这个按钮时,输出控制台返回这个错误:

Trying to start MapKit location updates without prompting for location authorization. Must call -[CLLocationManager requestWhenInUseAuthorization] or -[CLLocationManager requestAlwaysAuthorization] first.

根据我的说法,此错误是由于 requestWhenInUseAuthorization() 尚未调用而引起的。事实上,MKUserTrackingBarButtonItem tap 调用函数 mapViewWillStartLocatingUser,它首先假定 CLLocationManager requestWhenInUseAuthorization:

 func mapViewWillStartLocatingUser(mapView: MKMapView!) {
    println("**** mapViewWillStartLocatingUser ****")

    // i servizi di localizzazione sono abilitati?
    if (CLLocationManager.locationServicesEnabled())
    {
        // setto il locationManager ed il delegate
        locationManager = CLLocationManager()
        locationManager.delegate = self

        // abbiamo l'autorizzazione ad accedere ai servizi di localizzazione?
        switch CLLocationManager.authorizationStatus(){
        case .Denied:
            // no
            displayAlertToEnableLocationServicesApp()
            //displayAlertWithTitle("Denied", message: "Location services are not allowed for this app")
        case .Restricted:
            // no
            displayAlertToEnableLocationServicesApp()
        case .NotDetermined:
            // bisogna chiedere all'utente
            println("Not Determined")
            if (locationManager != nil)
            {
                locationManager.requestWhenInUseAuthorization()
            }
        default:
            // si
            println("Authorized")
            if (locationManager != nil)
            {
                locationManager.desiredAccuracy = kCLLocationAccuracyBest
                locationManager.startUpdatingLocation()
            }
        }

    }
    else
    {
        println("Location services are not enabled")

        displayAlertWithTitle("Location Services are Turned Off", message: "Please open settings and turn on location services")
    }
}

// funzione della mappa
func mapView(mapView: MKMapView!, didFailToLocateUserWithError error: NSError!) {
    println("**** didFailToLocateUserWithError **** ", error)
}

// funzione della mappa
func mapView(mapView: MKMapView!, didChangeUserTrackingMode mode: MKUserTrackingMode, animated: Bool) {
    println("**** didChangeUserTrackingMode ****")
}

// funzione del CoreLocation che setta la visuale in base alla localizzaizone dell'utente
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
    println("**** didUpdateLocations ****")

    //self.mapView.showsUserLocation = true


    // aggiorno le coordinate dell'utente
    posizioneUtente = (locations[0] as CLLocation).coordinate
    //posizioneUtente = manager.location.coordinate
    println("Posizione utente aggiornata (lat: \(posizioneUtente.latitude) long: \(posizioneUtente.longitude))")

    // setto la camera sulla posizione dell'utente
    var camera = MKMapCamera(lookingAtCenterCoordinate: posizioneUtente, fromEyeCoordinate: posizioneUtente, eyeAltitude: 500)
    // utilizzo un'animazione più lenta
    UIView.animateWithDuration(1.8, animations:{
        self.mapView.camera = camera
    })

    locationManager.stopUpdatingLocation()

    // cambio l'icona del bottone della localizzazione
    //locationOutlet.setImage(UIImage(named: "LocalizzazioneEmpty"), forState: UIControlState.Normal)

}



// funzione del CoreLocation
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!)
{
    println("**** didFailWithError ****")
    println("Error: \(error.localizedDescription)")
}

// funzione del CoreLocation
func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
    print("The authorization status of location " + "services is changed to: ")

    switch CLLocationManager.authorizationStatus(){
    case .Denied:
        println("Denied")
    case .NotDetermined:
        println("Not determined")
    case .Restricted:
        println("Restricted")
    default:
        println("Authorized")
    }
}

我自然地添加了 Info.plist 键: NSLocationWhenInUseUsageDescription 。

我的问题是:如何在 MKUserTrackingBarButtonItem 点击但在 mapViewWillStartLocatingUser 启动之前调用 CLLocationManager requestWhenInUseAuthorization。我希望用户在点击按钮时得到提示,而 viewDidLoad

中没有

谢谢 对不起我的英语

最佳答案

当您调用 requestWhenInUseAuthorization 时,系统会提示用户提供权限,但该权限尚未获得授权。一旦用户授予该权限,该问题将不会再次出现。

要对用户的响应使用react,您必须实现 locationManager(_:didChangeAuthorizationStatus:) 来自 CLLocationManagerDelegate 协议(protocol),只有在用户授予权限时才启动 startUpdateLocations()

关于swift - 尝试在不提示位置授权的情况下启动 MapKit 位置更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29396679/

有关swift - 尝试在不提示位置授权的情况下启动 MapKit 位置更新的更多相关文章

  1. ruby - ECONNRESET (Whois::ConnectionError) - 尝试在 Ruby 中查询 Whois 时出错 - 2

    我正在用Ruby编写一个简单的程序来检查域列表是否被占用。基本上它循环遍历列表,并使用以下函数进行检查。require'rubygems'require'whois'defcheck_domain(domain)c=Whois::Client.newc.query("google.com").available?end程序不断出错(即使我在google.com中进行硬编码),并打印以下消息。鉴于该程序非常简单,我已经没有什么想法了-有什么建议吗?/Library/Ruby/Gems/1.8/gems/whois-2.0.2/lib/whois/server/adapters/base.

  2. ruby - 默认情况下使选项为 false - 2

    这是在Ruby中设置默认值的常用方法:classQuietByDefaultdefinitialize(opts={})@verbose=opts[:verbose]endend这是一个容易落入的陷阱:classVerboseNoMatterWhatdefinitialize(opts={})@verbose=opts[:verbose]||trueendend正确的做法是:classVerboseByDefaultdefinitialize(opts={})@verbose=opts.include?(:verbose)?opts[:verbose]:trueendend编写Verb

  3. ruby - 在没有 sass 引擎的情况下使用 sass 颜色函数 - 2

    我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re

  4. ruby-on-rails - 启动 Rails 服务器时 ImageMagick 的警告 - 2

    最近,当我启动我的Rails服务器时,我收到了一长串警告。虽然它不影响我的应用程序,但我想知道如何解决这些警告。我的估计是imagemagick以某种方式被调用了两次?当我在警告前后检查我的git日志时。我想知道如何解决这个问题。-bcrypt-ruby(3.1.2)-better_errors(1.0.1)+bcrypt(3.1.7)+bcrypt-ruby(3.1.5)-bcrypt(>=3.1.3)+better_errors(1.1.0)bcrypt和imagemagick有关系吗?/Users/rbchris/.rbenv/versions/2.0.0-p247/lib/ru

  5. ruby-on-rails - 每次我尝试部署时,我都会得到 - (gcloud.preview.app.deploy) 错误响应 : [4] DEADLINE_EXCEEDED - 2

    我是Google云的新手,我正在尝试对其进行首次部署。我的第一个部署是RubyonRails项目。我基本上是在关注thisguideinthegoogleclouddocumentation.唯一的区别是我使用的是我自己的项目,而不是他们提供的“helloworld”项目。这是我的app.yaml文件runtime:customvm:trueentrypoint:bundleexecrackup-p8080-Eproductionconfig.ruresources:cpu:0.5memory_gb:1.3disk_size_gb:10当我转到我的项目目录并运行gcloudprevie

  6. ruby - 在不使用 RVM 的情况下在 Mac 上卸载和升级 Ruby - 2

    我最近决定从我的系统中卸载RVM。在thispage提出的一些论点说服我:实际上,我的决定是,我根本不想担心Ruby的多个版本。我只想使用1.9.2-p290版本而不用担心其他任何事情。但是,当我在我的Mac上运行ruby--version时,它告诉我我的版本是1.8.7。我四处寻找如何简单地从我的Mac上卸载这个Ruby,但奇怪的是我没有找到任何东西。似乎唯一想卸载Ruby的人运行linux,而使用Mac的每个人都推荐RVM。如何从我的Mac上卸载Ruby1.8.7?我想升级到1.9.2-p290版本,并且我希望我的系统上只有一个版本。 最佳答案

  7. UE4 源码阅读:从引擎启动到Receive Begin Play - 2

    一、引擎主循环UE版本:4.27一、引擎主循环的位置:Launch.cpp:GuardedMain函数二、、GuardedMain函数执行逻辑:1、EnginePreInit:加载大多数模块int32ErrorLevel=EnginePreInit(CmdLine);PreInit模块加载顺序:模块加载过程:(1)注册模块中定义的UObject,同时为每个类构造一个类默认对象(CDO,记录类的默认状态,作为模板用于子类实例创建)(2)调用模块的StartUpModule方法2、FEngineLoop::Init()1、检查Engine的配置文件找出使用了哪一个GameEngine类(UGame

  8. ruby - 正则表达式在哪个位置失败? - 2

    我需要一个非常简单的字符串验证器来显示第一个符号与所需格式不对应的位置。我想使用正则表达式,但在这种情况下,我必须找到与表达式相对应的字符串停止的位置,但我找不到可以做到这一点的方法。(这一定是一种相当简单的方法……也许没有?)例如,如果我有正则表达式:/^Q+E+R+$/带字符串:"QQQQEEE2ER"期望的结果应该是7 最佳答案 一个想法:你可以做的是标记你的模式并用可选的嵌套捕获组编写它:^(Q+(E+(R+($)?)?)?)?然后你只需要计算你获得的捕获组的数量就可以知道正则表达式引擎在模式中停止的位置,你可以确定匹配结束

  9. ruby - 在什么情况下会使用 Sinatra 或 Merb? - 2

    我正在学习Rails,对Sinatra和Merb知之甚少。我想知道您会在哪些情况下使用Merb/Sinatra。感谢您的反馈! 最佳答案 Sinatra是一个比Rails更小、更轻的框架。如果你想让一些东西快速运行,只需发送几个URL并返回一些简单的内容,就可以使用它。看看Sinatrahomepage;这就是启动和运行“Hello,World”所需的全部内容,而在Rails中,您需要生成整个项目结构、设置Controller和View、设置路由等等(我还没有有一段时间写了一个Rails应用程序,所以我不知道“Hello,World

  10. ruby - 是否可以在不实际发送或读取数据的情况下查明 ruby​​ 套接字是否处于 ESTABLISHED 或 CLOSE_WAIT 状态? - 2

    s=Socket.new(Socket::AF_INET,Socket::SOCK_STREAM,0)s.connect(Socket.pack_sockaddr_in('port','hostname'))ssl=OpenSSL::SSL::SSLSocket.new(s,sslcert)ssl.connect从这里开始,如果ssl连接和底层套接字仍然是ESTABLISHED,或者它是否在默认值7200之后进入CLOSE_WAIT,我想检查一个线程几秒钟甚至更糟的是在实际上不需要.write()或.read()的情况下关闭。是用select()、IO.select()还是其他方法完成

随机推荐