【问题标题】:CoreLocation requestWhenInUseAuthorization flashes for a second and then disappears, or just doesn't showCoreLocation requestWhenInUseAuthorization 闪烁一秒钟然后消失,或者只是不显示
【发布时间】:2021-06-25 00:41:00
【问题描述】:

我正在尝试设置我的模拟器以批准核心位置。有几次我确实弹出了权限窗口,但在我选择“使用中”选项之前它很快就消失了。

我已经根据我在这里看到的其他类似问题和 wenderlich 演练尝试了以下内容...

  1. 功能 > 位置 > 苹果
  2. Info Plist 包含用于...的条目
  3. 删除应用并:

设置 > 常规 > 重置 > 重置位置和隐私

在 Xcode 12.4、Swift 5.1、iPhone SE - 第二代 - iOS 14.4 模拟器上使用以下代码...

import SwiftUI
import CoreLocation

struct ContentView: View {

    @Environment(\.managedObjectContext) private var viewContext

    func setupCL() {
        let locationManager = CLLocationManager()
        let clDelegate = CLDelegate()
        locationManager.delegate = clDelegate
        if locationManager.authorizationStatus == .notDetermined {
            locationManager.requestWhenInUseAuthorization()
        }
    }

    var body: some View {
        Button(action: {setupCL()}, label: {
            Text("Button")
        })
    }
}

class CLDelegate: NSObject, CLLocationManagerDelegate { }

我错过了什么?

【问题讨论】:

    标签: swift authorization core-location


    【解决方案1】:

    您的locationManager 和委托立即超出范围,因为您在视图上的函数中调用它们并且没有将它们保留在任何地方。将它们移动到 ObservableObject 使一切正常:

    
    class Manager : ObservableObject {
        let locationManager = CLLocationManager()
        let clDelegate = CLDelegate()
        
        func setupCL() {
            locationManager.delegate = clDelegate
            if locationManager.authorizationStatus == .notDetermined {
                locationManager.requestWhenInUseAuthorization()
            }
        }
    }
    
    struct ContentView: View {
    
       @StateObject private var manager = Manager()
    
        var body: some View {
            Button(action: {manager.setupCL()}) {
                Text("Button")
            }
        }
    }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多