gpt4 book ai didi

Swift,NSObject 中的 CLLocationManagerDelegate 不起作用

转载 作者:搜寻专家 更新时间:2023-10-31 22:51:04 24 4
gpt4 key购买 nike

我在使用 CLLocationDelegate 获取我的位置时遇到问题。我创建了 UIView 的新子类并且运行良好,但是当我创建 NSObject 的子类时,未调用 CLLocationDelegate。我可以找到问题所在。这是我的代码:

import UIKit
import CoreLocation

class LocationData: NSObject, CLLocationManagerDelegate {

var locationManager : CLLocationManager = CLLocationManager()

override init() {
super.init()
if self.locationManager.respondsToSelector(Selector("requestAlwaysAuthorization")) {
self.locationManager.requestWhenInUseAuthorization()
}
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.distanceFilter = 50
self.locationManager.startUpdatingLocation()
println("init LocationData")
}

func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
println(error.description)
}

func locationManager(manager: CLLocationManager!, didUpdateToLocation newLocation: CLLocation!, fromLocation oldLocation: CLLocation!) {
println("updated")
}
}

谢谢!

最佳答案

您的代码没问题!但是在实例化类时,你需要这样做:

 import UIKit

class ViewController: UIViewController {

let LocationData: LocationData = LocationData() //<- here is the secret to works!!!

override func viewDidLoad() {
super.viewDidLoad()
}

我还建议您将 init 更改为如下内容:

override init() {
super.init()

let authorizationStatus: CLAuthorizationStatus = CLLocationManager.authorizationStatus()

if authorizationStatus == .notDetermined {
locationManager.requestWhenInUseAuthorization()
}

self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.distanceFilter = 50
self.locationManager.startUpdatingLocation()
print("init LocationData")
}

并且不要忘记在 info.plist 项目中添加 NSLocationWhenInUseUsageDescription

关于Swift,NSObject 中的 CLLocationManagerDelegate 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28421050/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com