需求:获取经纬度。

方案:我自定义了一个类模块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()

定位框一闪而过 iOS Swift的更多相关文章

  1. iOS swift的xcworkspace多项目管理(架构思想)

    iOS  swift的xcworkspace多项目管理(架构思想) 技术说明: 今天在这里分享 swift下的 xcworkspace多项目管理(架构思想),能为我们在开发中带来哪些便捷?能为我们对整 ...

  2. iOS Swift 模块练习/swift基础学习

    SWIFT项目练习     SWIFT项目练习2 iOS Swift基础知识代码 推荐:Swift学习使用知识代码软件 0.swift中的宏定义(使用方法代替宏) 一.视图  +控件 1.UIImag ...

  3. ios swift 实现饼状图进度条,swift环形进度条

    ios swift 实现饼状图进度条 // // ProgressControl.swift // L02MyProgressControl // // Created by plter on 7/2 ...

  4. Building gRPC Client iOS Swift Note Taking App

    gRPC is an universal remote procedure call framework developed by Google that has been gaining inter ...

  5. iOS Swift WisdomScanKit图片浏览器功能SDK

    iOS Swift WisdomScanKit图片浏览器功能SDK使用 一:简介      WisdomScanKit 由 Swift4.2版编写,完全兼容OC项目调用. WisdomScanKit的 ...

  6. iOS Swift WisdomScanKit二维码扫码SDK,自定义全屏拍照SDK,系统相册图片浏览,编辑SDK

    iOS Swift WisdomScanKit 是一款强大的集二维码扫码,自定义全屏拍照,系统相册图片编辑多选和系统相册图片浏览功能于一身的 Framework SDK [1]前言:    今天给大家 ...

  7. iOS Swift WisdomHUD 提示界面框架

    iOS Swift WisdomHUD 提示界面框架  Framework Use profile(应用简介) 一:WisdomHUD简介 今天给大家介绍一款iOS的界面显示器:WisdomHUD,W ...

  8. iOS Swift WisdomKeyboardKing 键盘智能管家SDK

    iOS Swift WisdomKeyboardKing 键盘智能管家SDK [1]前言:    今天给大家推荐个好用的开源框架:WisdomKeyboardKing,方面iOS日常开发,优点和功能请 ...

  9. iOS swift项目IM实现,从长连接到数据流解析分析之Socket

    iOS  swift项目IM实现,从长连接到底层数据解析分析之Socket 一:项目简介:  去年开始接手了一个国企移动项目,项目的需求是实现IM即时通讯功能. * 一期版本功能包括了:       ...

随机推荐

  1. swift 学习笔记

    1. 数组中取出字符串的方法: 1)let string = "\arr[0]" 2) let string = String(stringInterpolationSegment ...

  2. Unicode简介

    计算机只能处理二进制,因此需要把文字表示为二进制才能被计算机理解和识别. 一般的做法是为每一个字母或汉字分配一个id,然后用二进制表示这个id,存在内存或磁盘中.计算机可以根据二进制数据知道这个id是 ...

  3. ListView之多种类型Item

    一.概述 一般而言,listview每个item的样式是一样的,但也有很多应用场景下不同位置的item需要不同的样式. 拿微信举例,前者的代表作是消息列表,而后者的典型则是聊天会话界面. 本文重点介绍 ...

  4. 【代码笔记】iOS-实现网络图片的异步加载和缓存

    代码: - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. se ...

  5. HTML最新标准HTML5小结

    写在前面 HTML5出来已经很久了,然而由于本人不是专业搞前端的,只知道有这个东西,具体概念有点模糊(其实就是一系列标准规范啦):因此去年(2015.11.09),专门对HTML5做了个简单的小结,今 ...

  6. Mac配置PHP

    前言 在MacOS中已经内置了PHP和Apache,所以不需要再额外安装它们,只需要简单几步即可运行PHP. 配置Apache 查看Apache版本: $ sudo apachectl -v 终端关闭 ...

  7. 关于Mysql 触发器

    首先,测试版本 Mysql 5.6. 然后再看触发器的语法 CREATE [DEFINER = { user | CURRENT_USER }] TRIGGER trigger_name trigge ...

  8. 2-部署phpmyadmin

    软件下载地址:https://files.phpmyadmin.net/phpMyAdmin/4.5.5.1/phpMyAdmin-4.5.5.1-all-languages.zip 解压软件 [ro ...

  9. node 异步回调解决方法之yield

    先看如何使用 使用的npm包为genny,npm 安装genny,使用 node -harmony 文件(-harmony 为使用es6属性启动参数) 启动项目 var genny= require( ...

  10. [转]How to override HandleUnauthorizedRequest in ASP.NET Core

    本文转自:http://quabr.com/40446028/how-to-override-handleunauthorizedrequest-in-asp-net-core I'm migrati ...