2016-08-19 37 views
1

我似乎無法讓我的CoreLocation在我的今日擴展中工作。我已經將CoreLocation框架添加到我的Today Extension中,並將必要的項目添加到plist(NSLocationAlwaysUsageDescription)並添加了一個默認位置,但它仍然不起作用。我正在嘗試打印日誌的緯度。CoreLocation不能在今天的擴展中工作

我是新來的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 
    ) 
} 
} 
+0

您是否獲得了位置權限警報? – firstinq

+0

是的,我確實收到該警報 – fellowProgrammer

回答

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> 
+0

謝謝,會嘗試! – fellowProgrammer