[英]iOS Swift: Request user location
我是 iOS Swift 的初學者,正在編寫 iOS Swift 代碼並使用 UIWebView 加載我的網頁。
我的網頁會要求用戶啟用用戶位置。
我想在 iOS Swift 代碼中做類似的行為(彈出一個對話框並說“TestApp 想要訪問您的位置。你同意嗎?”)
我在模擬器上運行,但在使用 CLLocationManager 時失敗了
以下是我的 Swift 代碼
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var customWebView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
if let url = NSURL(string: "http://ctrlq.org/maps/where/") {
let request = NSURLRequest(URL: url)
customWebView.loadRequest(request)
let locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
有人知道如何請求位置嗎?
提前致謝。
埃里克
請求和更新用戶位置的正確方法是通過CLLocationManagerDelegate
。
雖然您的視圖控制器繼承了CLLocationManagerDelegate
,但它似乎沒有實現必要的委托功能。 正如@Rob 所提到的,您應該將 locationManager 聲明為類屬性,而不是局部變量。
如果/當用戶更改授權狀態時,此委托函數允許您實現邏輯:
func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if status == .AuthorizedWhenInUse {
// authorized location status when app is in use; update current location
locationManager.startUpdatingLocation()
// implement additional logic if needed...
}
// implement logic for other status values if needed...
}
如果/當用戶位置發生變化時,此委托函數允許您實現邏輯:
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
if let location = locations.first as? CLLocation {
// implement logic upon location change and stop updating location until it is subsequently updated
locationManager.stopUpdatingLocation()
}
}
此外, locationServicesEnabled()
確定用戶是否啟用了位置服務。
你在 didFinishLaunchingWithOptions 中顯示 call 做這樣的事情
let status = CLLocationManager.authorizationStatus()
if status == .NotDetermined || status == .Denied || status == .AuthorizedWhenInUse {
// present an alert indicating location authorization required
// and offer to take the user to Settings for the app via
// UIApplication -openUrl: and UIApplicationOpenSettingsURLString
dispatch_async(dispatch_get_main_queue(), {
let alert = UIAlertController(title: "Error!", message: "GPS access is restricted. In order to use tracking, please enable GPS in the Settigs app under Privacy, Location Services.", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Go to Settings now", style: UIAlertActionStyle.Default, handler: { (alert: UIAlertAction!) in
print("")
UIApplication.sharedApplication().openURL(NSURL(string:UIApplicationOpenSettingsURLString)!)
}))
// self.presentViewController(alert, animated: true, completion: nil)
self.window?.rootViewController?.presentViewController(alert, animated: true, completion: nil)
})
locationManager.requestAlwaysAuthorization()
locationManager.requestWhenInUseAuthorization()
}
一些想法:
您已將CLLocationManager
定義為局部變量,當它超出范圍時將被釋放。
將此作為您班級的屬性。
如果您確實需要requestAlwaysAuthorization
,請不要忘記按照NSLocationAlwaysUsageDescription
中的概述在 plist 中設置NSLocationAlwaysUsageDescription
。
(如果您不需要始終授權,但可以使用“使用中”授權,請調用requestWhenInUseAuthorization
並設置NSLocationWhenInUseUsageDescription
值。)
您需要在您的 info.plist 文件中添加一個鍵 NSLocationWhenInUseUsageDescription 並在您編寫要在彈出對話框中向用戶顯示的內容的值中。 您需要在真實設備上對其進行測試,因為 Simulator 僅接受自定義位置。 選擇模擬器 -> 調試 -> 位置 -> 自定義位置...
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
let locationManager = CLLocationManager()
@IBOutlet weak var webview: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
let url = NSURL (string: "http://www.your-url.com");
let requestObj = NSURLRequest(URL: url!);
webview.loadRequest(requestObj);
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: {(placemarks, error)->Void in
if (error != nil) {
print("Error: " + error!.localizedDescription)
return
}
if placemarks!.count > 0 {
let pm = placemarks![0] as CLPlacemark
self.displayLocationInfo(pm)
} else {
print("Error with the data.")
}
})
}
func displayLocationInfo(placemark: CLPlacemark) {
self.locationManager.stopUpdatingLocation()
print(placemark.locality)
print(placemark.postalCode)
print(placemark.administrativeArea)
print(placemark.country)
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
print("Error: " + error.localizedDescription)
}
}
嘗試這個
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
let locationManager = CLLocationManager()
@IBOutlet weak var webview: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
let url = NSURL (string: "http://www.your-url.com");
let requestObj = NSURLRequest(URL: url!);
webview.loadRequest(requestObj);
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: {(placemarks, error)->Void in
if (error != nil) {
print("Error: " + error!.localizedDescription)
return
}
if placemarks!.count > 0 {
let pm = placemarks![0] as CLPlacemark
self.displayLocationInfo(pm)
} else {
print("Error with the data.")
}
})
}
func displayLocationInfo(placemark: CLPlacemark) {
self.locationManager.stopUpdatingLocation()
print(placemark.locality)
print(placemark.postalCode)
print(placemark.administrativeArea)
print(placemark.country)
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
print("Error: " + error.localizedDescription)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.