2016-11-25 65 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