【问题标题】:Cannot get position from iOS simulator无法从 iOS 模拟器获取位置
【发布时间】:2015-05-24 14:52:28
【问题描述】:

我正在尝试通过简单的快速代码使用 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()
    }
}

【问题讨论】:

  • 问题:你想得到的位置是……究竟是什么?
  • 不要添加虚拟段落以使帖子更长,您应该更多地解释问题,并且可能会说一些关于 GPS 之类的...

标签: ios swift core-location


【解决方案1】:

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

列表

【讨论】:

  • 在 iOS8 中,需要在 Info.plist 文件中添加 NSLocationWhenInUseUsageDescription 或 NSLocationAlwaysUsageDescription 键值对。
  • 我在 iOS 模拟器中设置了位置。我将 NSLocationWhenInUseUsageDescription 键添加到 pList。但是没有调用回调函数。
  • 我注意到你没有设置精度,也许这是问题尝试添加 locMan.desiredAccuracy = kCLLocationAccuracyBest,就在你将代理设置为 self 之后。让我知道它是否适合您。
  • 感谢您的英勇建议。我可以得到纬度和经度。
猜你喜欢
  • 1970-01-01
  • 2016-02-28
  • 1970-01-01
  • 2014-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-03
  • 1970-01-01
相关资源
最近更新 更多