2015-02-03 19 views
6

Sono un principiante in iOS Swift e in scrittura codice iOS Swift e utilizzo di UIWebView per caricare la mia pagina Web.iOS Swift: Richiedi posizione utente

E la mia pagina web sarà chiederà all'utente di attivare la posizione dell'utente.

Mi piacerebbe fare il comportamento simile in iOS codice Swift (popup una finestra e dire qualcosa come "TestApp vorrebbe accedere alla tua posizione. Sarebbe d'accordo?")

Io corro su Simulatore e ho fallito durante l'utilizzo di CLLocationManager

Il seguente è il mio codice 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. 
} 

} 

qualcuno sa come richiedere posizione?

Grazie in anticipo.

Eric

+0

Controllare NSHipster fuori per una buona sintesi (per iOS 8, ma ancora valido). Il loro articolo parla della necessità di impostare la chiave in info.plist: [NSHipster - Core Location in i OS 8] (http://nshipster.com/core-location-in-ios-8/) Inoltre, _The prompt utente contiene il testo dalla chiave NSLocationWhenInUseUsageDescription nel file Info.plist dell'app e la presenza di tale chiave è richiesta quando si chiama questo metodo._ da [Riferimento classe CLLocationManager] (https://developer.apple.com/library/ ios/documentation/CoreLocation/Reference/CLLocationManager_Class /) – leanne

risposta

5

Un paio di pensieri:

  1. Hai definito la tua CLLocationManager come una variabile locale, che andranno rilasciato quando si cade fuori del campo di applicazione.

    Imposta come proprietà di classe.

  2. Se davvero bisogno requestAlwaysAuthorization, non dimenticate di impostare il NSLocationAlwaysUsageDescription nel plist come descritto nella documentazione.

    (E se non avete bisogno sempre l'autorizzazione, ma sono ok con autorizzazione "in uso", chiamare requestWhenInUseAuthorization e impostare il valore NSLocationWhenInUseUsageDescription.)

6

Il modo corretto per richiedere e posizione utente di aggiornamento (s) è via CLLocationManagerDelegate.

Mentre il View Controller eredita CLLocationManagerDelegate, sembra che non implementi le necessarie funzioni di delega. Come menzionato da @Rob, dovresti dichiarare locationManager come proprietà di classe, non come variabile locale.

Questa funzione delegato consente di implementare la logica se/quando l'utente cambia stato di autorizzazione:

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

Questa funzione delegato consente di implementare la logica se/quando posizione dell'utente è cambiato:

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

Inoltre, locationServicesEnabled() determina se l'utente ha abilitato i servizi di localizzazione.

1

È necessario aggiungere una chiave NSLocationWhenInUseUsageDescription nel proprio file info.plist e nel valore si scrive qualcosa che si desidera mostrare all'utente nella finestra di dialogo popup. È necessario testarlo su un dispositivo reale poiché Simulator accetta solo posizioni personalizzate. Seleziona il simulatore -> Debug -> Posizione -> Percorso personalizzato ...

+1

Mentre le altre risposte danno buoni consigli per lavorare con il gestore di posizione, questa risposta fornisce un pezzo "chiave" che l'OP probabilmente mancava. È necessario fornire il valore chiave appropriato nel file info.plist. Per quanto riguarda il simulatore, tuttavia, è possibile testare il messaggio che l'OP voleva vedere utilizzando il simulatore, indipendentemente dalle impostazioni di posizione personalizzate. – leanne

-1

provare questo

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

Si mostra chiamata fare qualcosa di simile in 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() 
    }