定位框一閃而過 iOS Swift


需求:獲取經緯度。

方案:我自定義了一個類模塊CLLocationModule.swift

備注以下代碼里 

let IS_IOS8 = (UIDevice.currentDevice().systemVersion as NSString).doubleValue >= 8.0

最開始的代碼

import UIKit

import CoreLocation

class CLLocationModule: NSObject ,CLLocationManagerDelegate{

    var latitude:Double?

    var longitude:Double?

    var city:NSString?

 

    func GetLatitudeLongitudeAndCity(){

        if CLLocationManager.locationServicesEnabled() == false {

            print("此設備不能定位")

            return

        }

        var locManager = CLLocationManager()        

        locManager.delegate = self

        locManager.desiredAccuracy = kCLLocationAccuracyBest        

        locManager.distanceFilter = 1000.0        

        //設置定位權限僅ios8有意義

        if IS_IOS8 {

            locManager.requestWhenInUseAuthorization()// 前台定位

            locManager.requestAlwaysAuthorization()

        }       

        locManager.startUpdatingLocation()

    }

    

    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        for location in locations {

            print("緯度:%g",location.coordinate.latitude);            

            print("經度:%g",location.coordinate.longitude);

            latitude = location.coordinate.latitude

            longitude = location.coordinate.longitude            

            self.saveLatitude(latitude!.description)

            self.saveLongitude(longitude!.description)            

            let geocoder: CLGeocoder = CLGeocoder()

            geocoder.reverseGeocodeLocation(location) { (placemarks, error) in

                if error != nil {

                    print("reverse geodcode fail: \(error!.localizedDescription)")

                    return

                }

                let pm = placemarks! as [CLPlacemark]

                if (pm.count > 0){

                    for placemark :CLPlacemark in placemarks! {                        

                        let placemarkDict = placemark.addressDictionary

                        let placemarkStr = placemarkDict!["State"]

                        self.city = placemarkStr?.substringToIndex((placemarkStr?.length)!-1)

                        self.saveCity(self.city!)

                    }

                }else{

                    print("No Placemarks!")

                }

            }

        }        

        manager.stopUpdatingLocation()

    }

   

    func locationManager(manager:CLLocationManager, didFailWithError error:NSError) {

        print("locationManager error");        

    }

    

    func saveLatitude(latitude: NSString) {

        let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()

        defaults.setObject(latitude, forKey: "latitude")

        defaults.synchronize()

    }

    

    func readLatitude() -> NSString {

        let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()

        let latitude = defaults.objectForKey("latitude") as! NSString

        return latitude;

    }

    

    func saveLongitude(longitude: NSString) {

        let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()

        defaults.setObject(longitude, forKey: "longitude")

        defaults.synchronize()

    }

    

    func readLongitude() -> NSString {

        let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()

        let longitude = defaults.objectForKey("longitude") as! NSString

        return longitude;

    }

    

    func saveCity(city: NSString) {

        let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()

        defaults.setObject(city, forKey: "city")

        defaults.synchronize()

    }

    

    func readCity() -> NSString {

        let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()

        let city = defaults.objectForKey("city") as! NSString

        return city;

    }

}

 

外部調用是:

CLLocationModule().GetLatitudeLongitudeAndCity()

結果:定位框一閃而過 (允許 不允許那個彈出框) 導致不走代理方法didUpdateLocations 最后查閱網頁 知道  

 

(a)locManager沒定義為全局變量 

(b)自定義的CLLocationModule.swift這個類 由於ARC的緣故 自動釋放了

針對以上(a)問題的解決辦法為自定義類CLLocationModule.swift中將var locManager = CLLocationManager() 改為全局變量

var locManager: CLLocationManager!

locManager = CLLocationManager()

針對以上(b)問題的解決方案有兩種

(1)外部調用時改為:(改為強引用)

var aCLLocationModule = CLLocationModule()

self.aCLLocationModule.GetLatitudeLongitudeAndCity()

(2)自定義的類CLLocationModule.swift改為單例

    //單例

    private static let aSharedInstance: CLLocationModule = CLLocationModule()

    private override init() {}

    class func sharedInstance() -> CLLocationModule {

        return aSharedInstance

    }

外部調用時改為:

CLLocationModule.sharedInstance().GetLatitudeLongitudeAndCity()

成功的代碼附上兩份

(1)單例

import UIKit

import CoreLocation

class CLLocationModule: NSObject ,CLLocationManagerDelegate{

     //單例

    private static let aSharedInstance: CLLocationModule = CLLocationModule()

    private override init() {}

    class func sharedInstance() -> CLLocationModule {

        return aSharedInstance

    }

    

    var locManager: CLLocationManager! 

    var latitude:Double?

    var longitude:Double?

    var city:NSString?

    

    func GetLatitudeLongitudeAndCity(){        

        if CLLocationManager.locationServicesEnabled() == false {

            print("此設備不能定位")

            return

        }

        locManager = CLLocationManager()       

        locManager.delegate = self       

        locManager.desiredAccuracy = kCLLocationAccuracyBest        

        locManager.distanceFilter = 1000.0

        //設置定位權限僅ios8有意義

        if IS_IOS8 {

            locManager.requestWhenInUseAuthorization()// 前台定位

            locManager.requestAlwaysAuthorization()

        }        

        locManager.startUpdatingLocation()

    }

    

    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        for location in locations {

            print("緯度:%g",location.coordinate.latitude);            

            print("經度:%g",location.coordinate.longitude);

            latitude = location.coordinate.latitude

            longitude = location.coordinate.longitude           

            self.saveLatitude(latitude!.description)

            self.saveLongitude(longitude!.description)         

            let geocoder: CLGeocoder = CLGeocoder()

            geocoder.reverseGeocodeLocation(location) { (placemarks, error) in

                if error != nil {

                    print("reverse geodcode fail: \(error!.localizedDescription)")

                    return

                }

                let pm = placemarks! as [CLPlacemark]

                if (pm.count > 0){

                    for placemark :CLPlacemark in placemarks! {

                        let placemarkDict = placemark.addressDictionary

                        let placemarkStr = placemarkDict!["State"]

                        self.city = placemarkStr?.substringToIndex((placemarkStr?.length)!-1)                        

                        self.saveCity(self.city!)

                    }

                }else{

                    print("No Placemarks!")

                }

            }

        }      

        manager.stopUpdatingLocation()

    }

   

    func locationManager(manager:CLLocationManager, didFailWithError error:NSError) {

        print("locationManager error");       

    }

    

    func saveLatitude(latitude: NSString) {

        let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()

        defaults.setObject(latitude, forKey: "latitude")

        defaults.synchronize()

    }

    

    func readLatitude() -> NSString {

        let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()

        let latitude = defaults.objectForKey("latitude") as! NSString

        return latitude;

    }

    

    func saveLongitude(longitude: NSString) {

        let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()

        defaults.setObject(longitude, forKey: "longitude")

        defaults.synchronize()

    }

    

    func readLongitude() -> NSString {

        let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()

        let longitude = defaults.objectForKey("longitude") as! NSString

        return longitude;

    }

    

    func saveCity(city: NSString) {

        let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()

        defaults.setObject(city, forKey: "city")

        defaults.synchronize()

    }

    

    func readCity() -> NSString {

        let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()

        let city = defaults.objectForKey("city") as! NSString

        return city;

    }

}

外部調用:

CLLocationModule.sharedInstance().GetLatitudeLongitudeAndCity()

(2)強引用

import UIKit

import CoreLocation

class CLLocationModule: NSObject ,CLLocationManagerDelegate{

    var locManager: CLLocationManager!   

    var latitude:Double?

    var longitude:Double?

    var city:NSString?

    

    func GetLatitudeLongitudeAndCity(){        

        if CLLocationManager.locationServicesEnabled() == false {

            print("此設備不能定位")

            return

        }

        locManager = CLLocationManager()        

        locManager.delegate = self        

        locManager.desiredAccuracy = kCLLocationAccuracyBest        

        locManager.distanceFilter = 1000.0       

        //設置定位權限僅ios8有意義

        if IS_IOS8 {

            locManager.requestWhenInUseAuthorization()// 前台定位

            locManager.requestAlwaysAuthorization()

        }      

        locManager.startUpdatingLocation()

    }

    

    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        for location in locations {

            print("緯度:%g",location.coordinate.latitude);            

            print("經度:%g",location.coordinate.longitude);

            latitude = location.coordinate.latitude

            longitude = location.coordinate.longitude            

            self.saveLatitude(latitude!.description)

            self.saveLongitude(longitude!.description)            

            let geocoder: CLGeocoder = CLGeocoder()

            geocoder.reverseGeocodeLocation(location) { (placemarks, error) in

                if error != nil {

                    print("reverse geodcode fail: \(error!.localizedDescription)")

                    return

                }

                let pm = placemarks! as [CLPlacemark]

                if (pm.count > 0){

                    for placemark :CLPlacemark in placemarks! {                        

                        let placemarkDict = placemark.addressDictionary

                        let placemarkStr = placemarkDict!["State"]

                        self.city = placemarkStr?.substringToIndex((placemarkStr?.length)!-1)                       

                        self.saveCity(self.city!)

                    }

                }else{

                    print("No Placemarks!")

                }

            }

        }        

        manager.stopUpdatingLocation()

    }

    

    func locationManager(manager:CLLocationManager, didFailWithError error:NSError) {        

        print("locationManager error");        

    }

    

    func saveLatitude(latitude: NSString) {

        let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()

        defaults.setObject(latitude, forKey: "latitude")

        defaults.synchronize()

    }

    

    func readLatitude() -> NSString {

        let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()

        let latitude = defaults.objectForKey("latitude") as! NSString

        return latitude;

    }

    

    func saveLongitude(longitude: NSString) {

        let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()

        defaults.setObject(longitude, forKey: "longitude")

        defaults.synchronize()

    }

    

    func readLongitude() -> NSString {

        let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()

        let longitude = defaults.objectForKey("longitude") as! NSString

        return longitude;

    }

    

    func saveCity(city: NSString) {

        let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()

        defaults.setObject(city, forKey: "city")

        defaults.synchronize()

    }

    

    func readCity() -> NSString {

        let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()

        let city = defaults.objectForKey("city") as! NSString

        return city;

    } 

}

外部調用:

var aCLLocationModule = CLLocationModule()

self.aCLLocationModule.GetLatitudeLongitudeAndCity()

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM