2016-11-25 42 views

回答

3

为了得到用户的当前位置,你需要声明:

let locationManager = CLLocationManager() 

在viewDidLoad中():

// Ask for Authorisation from the User. 
    self.locationManager.requestAlwaysAuthorization() 

    // For use in foreground 
    self.locationManager.requestWhenInUseAuthorization() 

    if CLLocationManager.locationServicesEnabled() { 
     locationManager.delegate = self 
     locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters 
     locationManager.startUpdatingLocation() 
    } 

然后在CLLocationManagerDelegate方法就可以得到用户的当前位置坐标:

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 
    var locValue:CLLocationCoordinate2D = manager.location.coordinate 
    print("locations = \(locValue.latitude) \(locValue.longitude)") 
} 

如果用户拒绝了该位置,然后给他选择更改位置pe从设置中删除:

func locationManager(manager: CLLocationManager, didFailWithError error: NSError) { 
    print("error::: \(error)") 
    locationManager.stopUpdatingLocation() 
    let alert = UIAlertController(title: "Settings", message: "Allow location from settings", preferredStyle: UIAlertControllerStyle.Alert) 
    self.presentViewController(alert, animated: true, completion: nil) 
    alert.addAction(UIAlertAction(title: TextMessages().callAlertTitle, style: .Default, handler: { action in 
     switch action.style{ 
     case .Default: UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString)!) 
     case .Cancel: print("cancel") 
     case .Destructive: print("destructive") 
     } 
    })) 
} 
0

不,您可以在提醒内部的应用程序中提醒他们,例如“为了更好的使用,我们会建议您给我们使用您的位置的权限”。并添加“转到设置”按钮,将用户重定向到应用程序的位置权限。

+0

这是认真的答案? –

+0

@NumanKaraaslan是的。如果你仔细阅读,你会发现这是接受答案的简短变体。 – Lexorus