无法从iOS模拟器获取位置

kun*_*255 -1 core-location ios swift

我试图通过简单的快速代码使用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()
    }
}
Run Code Online (Sandbox Code Playgroud)

Ica*_*aro 7

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

在此输入图像描述

plist中

在此输入图像描述

  • 在iOS8中,需要将NSLocationWhenInUseUsageDescription或NSLocationAlwaysUsageDescription键值对添加到Info.plist文件中. (2认同)