公司需求需要在图片上显示拍照的时间和地点的水印,刚开始想用第三方如百度或高德,但是只有这么一个小需求,如果拉入第三方感觉不太好,所有就用了系统自带的地图CoreLocation.
1.首先导入系统库"import CoreLocation"
2.实现代码
11 // 需要导入CoreLocation框架
12 import CoreLocation
13
14 class ViewController: UIViewController,CLLocationManagerDelegate {
15
16 // 声明一个全局变量
17 var locationManager:CLLocationManager!
18
19 override func viewDidLoad() {
20 super.viewDidLoad()
21 locationManager = CLLocationManager()
22
23 // 设置定位的精确度
24 locationManager.desiredAccuracy = kCLLocationAccuracyBest
25
26 // 设置定位变化的最小距离 距离过滤器
27 locationManager.distanceFilter = 50
28
29 // 设置请求定位的状态
30 if #available(iOS 8.0, *) {
31 locationManager.requestWhenInUseAuthorization()
32 } else {
33 // Fallback on earlier versions
34 print("hello")
35 }//这个是在ios8之后才有的
36
37 // 设置代理为当前对象
38 locationManager.delegate = self;
39
40 if CLLocationManager.locationServicesEnabled(){
41 // 开启定位服务
42 locationManager.startUpdatingLocation()
43 }else{
44 print("没有定位服务")
45 }
46
47 }
48 // 定位失败调用的代理方法
49 func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
50 print(error)
51 }
52 // 定位更新地理信息调用的代理方法
53 func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
54 if locations.count > 0
55 {
56 let locationInfo = locations.last!
57 let alert:UIAlertView = UIAlertView(title: "获取的地理坐标",
58 message: "经度是:\(locationInfo.coordinate.longitude),维度是:\(locationInfo.coordinate.latitude)",
59 delegate: nil, cancelButtonTitle: "是的")
60 alert.show()
61 }
62 }
63 }
最后 这里只是获取了经纬, 要显示地理位置还需要转义,这段代码需要添加在跟新地理位置的信息的代理方法中,代码如下
let clGeoCoder = CLGeocoder()
//这里是传值是经纬度
let cl = CLLocation(latitude: (location?.coordinate.latitude)!, longitude: (location?.coordinate.longitude)!)
clGeoCoder.reverseGeocodeLocation(cl, completionHandler: { (placemarks, error) in
if placemarks != nil {
let placeMark = placemarks?.last
let addressDic:NSDictionary = placeMark!.addressDictionary as! [String:AnyObject] as NSDictionary
let state = addressDic.object(forKey: "State")//省会
let City = addressDic.object(forKey: "City")//城市
let SubLocality = addressDic.object(forKey: "SubLocality")//区域
let Street = addressDic.object(forKey: "Street")//街道名称
})