iOS Swift:请求用户位置

时间:2015-02-03 04:40:53

标签: ios swift uiwebview core-location

我是iOS Swift的初学者,编写iOS Swift代码并使用UIWebView加载我的网页。

我的网页将要求用户启用用户位置

我想在iOS Swift代码中执行类似的操作(弹出一个对话框并说“TestApp想要访问您的位置。你同意吗?”)

我在Simulator上运行,但在使用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.
}

}

任何人都知道如何申请地点?

提前致谢。

埃里克

6 个答案:

答案 0 :(得分:7)

请求和更新用户位置的正确方法是CLLocationManagerDelegate

当您的View Controller继承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()确定用户是否启用了位置服务。

答案 1 :(得分:7)

你在didFinishLaunchingWithOptions

中显示调用做这样的事情
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()
    }

答案 2 :(得分:6)

有几点想法:

  1. 您已将CLLocationManager定义为本地变量,当它超出范围时会被释放。

    将此属性设为。

  2. 如果您确实需要requestAlwaysAuthorization,请不要忘记在文档中概述的plist中设置NSLocationAlwaysUsageDescription

    (如果您不需要经常授权,但可以使用"正在使用"授权,请致电requestWhenInUseAuthorization并设置NSLocationWhenInUseUsageDescription值。)

答案 3 :(得分:3)

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)
    }


}

答案 4 :(得分:2)

您需要在您的info.plist文件中添加一个密钥NSLocationWhenInUseUsageDescription,并在您编写的值中添加要在弹出对话框中显示该用户的内容。 您需要在真实设备上测试它,因为Simulator只接受自定义位置。 选择模拟器 - >调试 - >位置 - >自定义位置......

答案 5 :(得分:-1)

试试这个

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)
}
}