无法从iOS模拟器获取位置

时间:2015-05-24 14:52:29

标签: ios swift core-location

我试图通过简单的快速代码使用iOS模拟器来获得位置。但是在调试会话中,不会调用回调函数。我将虚拟位置设置为iOS模拟器。

//  ViewController.swift
//  helloWorld
//
//  Created by  on 5/17/15.
//  Copyright (c) 2015   All rights reserved.
//

import UIKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {

    var locMan: CLLocationManager!
    var lat: CLLocationDegrees!
    var lng: CLLocationDegrees!
    var hasPosData: Bool

    required init(coder aDecoder: NSCoder) {
        locMan  = CLLocationManager()
        lat = CLLocationDegrees()
        lng = CLLocationDegrees()
        hasPosData = false
        super.init(coder: aDecoder)
    }

    func retreiveCurrentPos(){
        locMan.delegate = self
        locMan.requestAlwaysAuthorization()

        // start using GPS function
        locMan.startUpdatingLocation()
    }

    func saveResult2File(){
        var contents: String

        let dirToSave = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as! Array<String>
        let file      = String(dirToSave[0]) + "pos.dat"
        if(hasPosData){
            contents = String(format:"lat: %f lng: %f", lat, lng)
        }else{
            contents = "Failed to retreive position data"
        }

        contents.writeToFile(file, atomically: true, encoding: NSUTF8StringEncoding, error: nil)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        retreiveCurrentPos()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func locationManager(manager: CLLocationManager!, didUpdateToLocation newLocation: CLLocation!, fromLocation oldLocation: CLLocation!) {
        lat = newLocation.coordinate.latitude
        lng = newLocation.coordinate.longitude
        hasPosData = true
        saveResult2File()
    }

    func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
        hasPosData = false
        saveResult2File()
    }
}

1 个答案:

答案 0 :(得分:7)

您需要在iOS模拟器中设置一个位置,默认情况下设置为none会导致应用程序崩溃,因为您在使用前没有检查它。 您还需要在pList NSLocationWhenInUseUsageDescription中添加一个键,以防您忘记。

enter image description here

的plist

enter image description here