我之前使用 ViewController 类来获取用户更新,但现在在扩展应用程序时我需要将它移动到另一个只处理所有位置更新的类。这是我现在使用的代码:
class ViewController: UIViewController, UITextFieldDelegate {
@IBAction func pickMeUpButton(sender: AnyObject) {
sendPushNotificationController().sendPushNotification("sendRequest",userLat: defaults.stringForKey("userLat")!, userLong: defaults.stringForKey("userLong")! )
}
@IBOutlet var numberForPickup: UITextField!
let defaults = NSUserDefaults.standardUserDefaults()
override func viewDidLoad() {
super.viewDidLoad()
self.numberForPickup.delegate = self
getLocationController().initLocation()
}
所以我创建了另一个名为 getLocationController 的类,其中包含一个应该启动位置更新的初始化函数。这是代码:
class getLocationController: UIViewController, CLLocationManagerDelegate {
var locationManager: CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func initLocation(){
print("Im in here")
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation) {
print("In location")
if UIApplication.sharedApplication().applicationState == .Active {
print("App in Foreground")
}else {
let Device = UIDevice.currentDevice()
let iosVersion = Double(Device.systemVersion) ?? 0
let iOS9 = iosVersion >= 9
if iOS9{
locationManager.allowsBackgroundLocationUpdates = true;
locationManager.pausesLocationUpdatesAutomatically = false;
}
//let iOS7 = iosVersion >= 7 && iosVersion < 8
print("App is backgrounded. New location is %@", newLocation)
}
}
}
现在打印了 initLocation 中的打印,但没有打印 didUpdateLocations 中的打印。我在 ViewController 类中使用了完全相同的代码,它运行得非常好。现在,当我试图将它移动到另一个类时,它现在实际上是电话上的一个 View ,但只是一个辅助类,它不起作用。有什么想法吗?
最佳答案
我没有看到您将 getLocationController 分配给 ViewController 中任何位置的变量。这意味着 getLocationController 将超出范围并被销毁,不是吗?这可以解释为什么回调 didUpdateToLocation 没有被调用。
尝试:
class ViewController: UITextFieldDelegate {
@IBAction func pickMeUpButton(sender: AnyObject) {
sendPushNotificationController().sendPushNotification("sendRequest",userLat: defaults.stringForKey("userLat")!, userLong: defaults.stringForKey("userLong")! )
}
@IBOutlet var numberForPickup: UITextField!
let defaults = NSUserDefaults.standardUserDefaults()
var glc:getLocationController // is this how it is in Swift?!
override func viewDidLoad() {
super.viewDidLoad()
self.numberForPickup.delegate = self
glc = getLocationController()
glc.initLocation()
}
关于ios - 调用函数 swift 时使用另一个类获取位置不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34467214/