手把手教你Today扩展(三):在扩展中使用定位功能
2016-01-07 本文已影响157人
Hollylord
1. 如何去除Today扩展左边的margin
![](https://img.haomeiwen.com/i532649/96dccd242ed8e2df.png)
如上图去除红色边框。
在Today的这个类中,重写下面这个方法:
func widgetMarginInsetsForProposedMarginInsets(defaultMarginInsets: UIEdgeInsets) -> UIEdgeInsets {
return UIEdgeInsetsZero
}
2. 单独测试Today扩展
![](https://img.haomeiwen.com/i532649/34708071803a4a23.png)
将target换成扩展再运行。
3. Today扩展获取地理位置
- 导入CoreLocation框架
import CoreLocation
- 修改Today的info
添加NSLocationWhenInUseUsageDescription字段在info中。
Paste_Image.png
- 在Today类viewDidLoad添加如下代码
var locationManager: CLLocationManager = CLLocationManager()
locationManager.delegate = self
if locationManager.respondsToSelector("requestWhenInUseAuthorization") {
//这个方法是当用户允许定位之后就立刻响应的
locationManager.requestWhenInUseAuthorization()
}
locationManager.startUpdatingLocation()
- 添加回掉方法
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location: CLLocation = locations.last!
city.text = "\(location.coordinate)"
}