import UIKit
import CoreLocation;
class UserLocation: NSObject {
var userPosition: CLLocationCoordinate2D?
let manager = CLLocationManager()
/// 獲取用戶位置授權(quán),定位用戶當前坐標
func startUserlocation() {
manager.delegate = self;
manager.desiredAccuracy = kCLLocationAccuracyBest; //設(shè)置精確度
manager.distanceFilter = 50 ; //重新定位變化距離
if #available(iOS 8, *) { //ios8 或更高
print("request");
//manager.requestWhenInUseAuthorization(); //當app進入前臺開始定位
manager.requestAlwaysAuthorization(); //請求始終進行定位
}
if !CLLocationManager.locationServicesEnabled() {
print("設(shè)備沒開啟定位");return;
}
manager.startUpdatingLocation(); //開始定位
print("start");
}
}
extension UserLocation: CLLocationManagerDelegate {
// 地理位置更新
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print(locations)
if(locations.count <= 0 ){
return;
}
print("定位定位")
let userPos = locations.last! as CLLocation //獲得最新一次定位信息
userPosition = userPos.coordinate
manager.stopUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
print(status);
}
//定位失敗
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
print(error);
}
}
如上:
寫了一個location類,然后再界面上點擊一個按鈕觸發(fā)定位:
func richScan(){
var test = UserLocation();
test.startUserlocation();
}
但是彈出請求權(quán)限接口后 一閃而過,根本來不及點。這是什么情況。。。
走同樣的路,發(fā)現(xiàn)不同的人生
test
被 釋放了,arc 的問題,設(shè)置一個成員變量強引用,如:self.test = UserLocation();
Correct answer upstairs.
Writing UserLocation as a singleton seems to solve the problem.
If this problem is not solved yet, please read this article http://www.cnblogs.com/huangzs/p/5334130... If it is not solved yet, please message me privately