Snip20170609_3.png
公司需求需要在圖片上顯示拍照的時(shí)間和地點(diǎn)的水印,剛開(kāi)始想用第三方如百度或高德,但是只有這么一個(gè)小需求,如果拉入第三方感覺(jué)不太好,所有就用了系統(tǒng)自帶的地圖CoreLocation.
1.首先導(dǎo)入系統(tǒng)庫(kù)"import CoreLocation"
2.實(shí)現(xiàn)代碼
11 // 需要導(dǎo)入CoreLocation框架
12 import CoreLocation
13
14 class ViewController: UIViewController,CLLocationManagerDelegate {
15
16 // 聲明一個(gè)全局變量
17 var locationManager:CLLocationManager!
18
19 override func viewDidLoad() {
20 super.viewDidLoad()
21 locationManager = CLLocationManager()
22
23 // 設(shè)置定位的精確度
24 locationManager.desiredAccuracy = kCLLocationAccuracyBest
25
26 // 設(shè)置定位變化的最小距離 距離過(guò)濾器
27 locationManager.distanceFilter = 50
28
29 // 設(shè)置請(qǐng)求定位的狀態(tài)
30 if #available(iOS 8.0, *) {
31 locationManager.requestWhenInUseAuthorization()
32 } else {
33 // Fallback on earlier versions
34 print("hello")
35 }//這個(gè)是在ios8之后才有的
36
37 // 設(shè)置代理為當(dāng)前對(duì)象
38 locationManager.delegate = self;
39
40 if CLLocationManager.locationServicesEnabled(){
41 // 開(kāi)啟定位服務(wù)
42 locationManager.startUpdatingLocation()
43 }else{
44 print("沒(méi)有定位服務(wù)")
45 }
46
47 }
48 // 定位失敗調(diào)用的代理方法
49 func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
50 print(error)
51 }
52 // 定位更新地理信息調(diào)用的代理方法
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: "獲取的地理坐標(biāo)",
58 message: "經(jīng)度是:\(locationInfo.coordinate.longitude)定嗓,維度是:\(locationInfo.coordinate.latitude)",
59 delegate: nil, cancelButtonTitle: "是的")
60 alert.show()
61 }
62 }
63 }
最后 這里只是獲取了經(jīng)緯, 要顯示地理位置還需要轉(zhuǎn)義,這段代碼需要添加在跟新地理位置的信息的代理方法中,代碼如下
let clGeoCoder = CLGeocoder()
//這里是傳值是經(jīng)緯度
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")//省會(huì)
let City = addressDic.object(forKey: "City")//城市
let SubLocality = addressDic.object(forKey: "SubLocality")//區(qū)域
let Street = addressDic.object(forKey: "Street")//街道名稱
})