【发布时间】:2015-08-05 02:55:16
【问题描述】:
我在 Swift 中的位置有问题。
在模拟器上工作正常,但在设备上不工作
我使用模拟器 iPhone 6 iOS 8.3 和设备 iPhone 6 iOS 8.3
我的代码:
import UIKit
import CoreLocation
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,
CLLocationManagerDelegate {
var window: UIWindow?
var locationManager: CLLocationManager! = nil
var isExecutingInBackground = false
func locationManager(manager: CLLocationManager!,
didUpdateToLocation newLocation: CLLocation!,
fromLocation oldLocation: CLLocation!){
if isExecutingInBackground{
println(newLocation);
locationManager.stopUpdatingLocation()
} else {
/* We are in the foreground. Do any processing that you wish */
}
}
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
{
locationManager = CLLocationManager()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.delegate = self
locationManager.startUpdatingLocation()
return true
}
func applicationDidEnterBackground(application: UIApplication) {
isExecutingInBackground = true
var timer = NSTimer.scheduledTimerWithTimeInterval(30, target: self, selector: Selector("update"), userInfo: nil, repeats: true)
/* Reduce the accuracy to ease the strain on
iOS while we are in the background */
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
}
func update() {
println("test");
locationManager.startUpdatingLocation()
}
func applicationWillEnterForeground(application: UIApplication) {
isExecutingInBackground = false
/* Now that our app is in the foreground again, let's increase the location
detection accuracy */
locationManager.desiredAccuracy = kCLLocationAccuracyBest
}
}
我想每 30 秒获取一次位置
那为什么不在设备上工作呢?
【问题讨论】:
-
在确认您拥有位置权限之前,您不应调用 startUpdatingLocation。
didUpdateToLocation也已弃用。最后,您的设备是否启用了定位服务?当您在后台时,NSTimer 不会执行,但无论如何它不会做任何事情 -
是的,定位服务已启用当我单击菜单按钮时,我得到了位置,但 30 秒后我无法获得位置
-
您不一定会每 30 秒获得一次位置更新。当您的位置变化超过报告阈值时,您会收到位置更新。你在移动你的设备吗?
-
是的,如果我搬家还是不行……
-
我做了一个对我有用的简单例子,从这里看:stackoverflow.com/a/35973586/3410437
标签: ios iphone swift location cllocationmanager