手把手教你Today扩展(三):在扩展中使用定位功能

1. 如何去除Today扩展左边的margin

Paste_Image.png

如上图去除红色边框。
在Today的这个类中,重写下面这个方法:

func widgetMarginInsetsForProposedMarginInsets(defaultMarginInsets: UIEdgeInsets) -> UIEdgeInsets {
        return UIEdgeInsetsZero
    }

2. 单独测试Today扩展

Paste_Image.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)"
        
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容