2015-02-03 17 views
6

Tôi là người mới bắt đầu trong iOS Swift và viết mã iOS Swift và sử dụng UIWebView để tải trang web của tôi.iOS Swift: Yêu cầu vị trí người dùng

Và trang web của tôi sẽ yêu cầu người dùng bật vị trí người dùng.

Tôi muốn làm những hành vi tương tự trong mã Swift iOS (bật lên một hộp thoại và nói điều gì đó như "TestApp muốn truy cập vị trí của bạn. Bạn có đồng ý không?")

Tôi đang chạy trên Simulator và tôi đã thất bại khi sử dụng CLLocationManager

sau đây là mã Swift tôi

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

} 

Bất cứ ai cũng biết làm thế nào để yêu cầu vị trí?

Xin cảm ơn trước.

Eric

+0

Kiểm tra NSHipster ra cho một bản tóm tắt tốt (dành cho iOS 8, nhưng vẫn còn hiệu lực). Bài viết của họ nói về yêu cầu thiết lập khóa trong info.plist: [NSHipster - Vị trí cốt lõi trong i OS 8] (http://nshipster.com/core-location-in-ios-8/) Ngoài ra, _The lời nhắc người dùng chứa văn bản từ khóa NSLocationWhenInUseUsageDescription trong tệp Info.plist của ứng dụng và sự hiện diện của khóa đó là bắt buộc khi gọi phương thức này._ từ [Tham chiếu lớp CLLocationManager] (https://developer.apple.com/library/ ios/documentation/CoreLocation/Reference/CLLocationManager_Class /) – leanne

Trả lời

5

Một vài suy nghĩ:

  1. Bạn đã xác định của bạn CLLocationManager như là một biến địa phương, sẽ được phát hành khi nó rơi ra khỏi phạm vi.

    Biến nó thành thuộc tính lớp.

  2. Nếu bạn thực sự cần requestAlwaysAuthorization, đừng quên đặt số NSLocationAlwaysUsageDescription trong danh sách như được nêu trong tài liệu.

    (Và nếu bạn không cần phải lúc nào cũng ủy quyền, nhưng là ok với "sử dụng" ủy quyền, gọi requestWhenInUseAuthorization và thiết lập giá trị NSLocationWhenInUseUsageDescription.)

6

Cách đúng yêu cầu và cập nhật vị trí người dùng (s) là qua CLLocationManagerDelegate.

Trong khi Trình điều khiển chế độ xem của bạn kế thừa CLLocationManagerDelegate, dường như không thực hiện các chức năng đại biểu cần thiết. Như đã đề cập bởi @Rob, bạn nên khai báo locationManager như một thuộc tính lớp, không phải là một biến cục bộ.

chức năng đại diện này cho phép bạn thực hiện logic nếu/khi người dùng thay đổi trạng thái ủy quyền:

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

chức năng đại diện này cho phép bạn thực hiện logic nếu/khi vị trí người dùng đã thay đổi:

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

Hơn nữa, locationServicesEnabled() xác định liệu người dùng có bật dịch vụ vị trí hay không.

1

Bạn cần thêm khóa NSLocationWhenInUseUsageDescription vào tệp info.plist của bạn và trong giá trị bạn viết thứ gì đó mà bạn muốn hiển thị người dùng trong hộp thoại bật lên. Bạn cần phải thử nghiệm nó trên một thiết bị thực sự gây ra Simulator chỉ chấp nhận vị trí tùy chỉnh. Chọn Trình mô phỏng -> Gỡ lỗi -> Vị trí -> Vị trí tùy chỉnh ...

+1

Trong khi các câu trả lời khác đưa ra lời khuyên tốt để làm việc với người quản lý vị trí, câu trả lời này cung cấp một phần "chìa khóa" mà OP có thể bị thiếu. Yêu cầu cung cấp giá trị khóa thích hợp trong tệp info.plist. Theo như mô phỏng đi, mặc dù - nó có thể kiểm tra cho các tin nhắn OP muốn xem bằng cách sử dụng giả lập, bất kể cài đặt vị trí tùy chỉnh. – leanne

-1

thử này

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


} 
5

Bạn hiển thị cuộc gọi làm một cái gì đó như thế này trong 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() 
    } 
Các vấn đề liên quan