CoreLocation在今天扩展中不起作用

时间:2016-08-19 21:07:01

标签: ios swift today-extension

我似乎无法让我的CoreLocation在我的Today Extension上工作。我已经将CoreLocation框架添加到了我的今日扩展,并将必要的项添加到plist(NSLocationAlwaysUsageDescription)并添加了一个默认位置,但它仍然无效。我正在尝试将纬度打印到日志中。

我是iOS编程的新手,任何帮助都将不胜感激!见下面的代码↓↓↓

import Foundation
import UIKit
import NotificationCenter
import CoreLocation

class WidgetViewController: UIViewController, NCWidgetProviding, CLLocationManagerDelegate {


var latitude: Double?
var longitude: Double?


var manager:CLLocationManager!


override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view from its nib.


    manager = CLLocationManager()
    manager.delegate = self
    manager.desiredAccuracy - kCLLocationAccuracyBest
    manager.requestAlwaysAuthorization()
    manager.startUpdatingLocation()


    delay(1.0) {
        print("\(self.latitude)")
    }


}

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

func widgetPerformUpdateWithCompletionHandler(completionHandler: ((NCUpdateResult) -> Void)) {
    // Perform any setup necessary in order to update the view.

    // If an error is encountered, use NCUpdateResult.Failed
    // If there's no update required, use NCUpdateResult.NoData
    // If there's an update, use NCUpdateResult.NewData

    completionHandler(NCUpdateResult.NewData)
}


// MARK: - Location Code

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    print(locations)

    //userLocation - there is no need for casting, because we are now using CLLocation object

    var userLocation:CLLocation = locations[0]


    latitude = (userLocation.coordinate.latitude)

    longitude = (userLocation.coordinate.longitude)


    CLGeocoder().reverseGeocodeLocation(userLocation, completionHandler: { (placemarks, error) -> Void in

        if (error != nil) {

            print(error)

        } else {

            if let p = placemarks?[0] {

                var subThoroughfare:String = ""

                if (p.subThoroughfare != nil) {

                    subThoroughfare = p.subThoroughfare!

                }


                print(p)

            }


        }

    })

}


func delay(delay: Double, closure: ()->()) {


    dispatch_after(
        dispatch_time(
            DISPATCH_TIME_NOW,
            Int64(delay * Double(NSEC_PER_SEC))
        ),
        dispatch_get_main_queue(),
        closure
    )
}
}

1 个答案:

答案 0 :(得分:0)

你可以做两件事:

  • 检查它是否适用于真实设备。
  • 或者使用gpx文件而不是Xcode构建方案中的预定义位置来模拟位置(我自己检查了它并且它有效)

示例gpx文件内容:

 
<gpx version="1.1" creator="Xcode"> 
  <wpt lat="47.52789018096815" lon="7.385249894876031"></wpt>
  <wpt lat="47.52720984945248" lon="7.382647784661411"></wpt>
</gpx>