Swift4 中的 CLLocationManager 单例
这主要是为了获取用户当前位置,本示例中在 Swift4 中使用单例类来共享位置服务。此类在用户通过使用完成块和错误处理自动更新当前位置时也将更新位置。
安装
将类文件夹拖放到您的 Xcode 项目中。您还可以使用 CocoaPods 或 Carthage。
使用 CocoaPods
首先请确保运行 pod repo update 获取最新版本。将 pod 'CoreLocationDemo' 添加到您的 Podfile,并运行 pod install。同时,将 use_frameworks! 添加到 Podfile。
- target 'MyApp'
- pod 'CoreLocationDemo', '~> 0.1.0'
- use_frameworks!
https://cocoapods.org.cn/pods/CoreLocationDemo
针对 Swift 4 更新
Swift 4 版本
要求
- 版本 9.2 或更高
- Apple LLVM 编译器
- 支持iOS 8.0或更高版本
- 自动引用计数(ARC)
安装
- 将LocationService.swift复制到您的项目中
- 在Info.plist文件中添加键“NSLocationAlwaysUsageDescription”,并将其值设置为任何您希望的消息。例如:“我们请求访问您手机的地理位置巴拉巴拉:(”或
- 如果您想在后台运行时正常访问用户的地理位置,请添加键“NSLocationWhenInUseUsageDescription”。
如何使用 - FetchLocation类
- 只需使用在ViewController类中使用的函数:self.fetchUserCurrentLocation().您必须在viewController或任何其他类中使用此函数。您将获得特定位置的当前位置。
如何使用 - 通过完成块获取实时位置
- 只需在ViewController类中调用以下函数
import CoreLocation
class ViewController: UIViewController
var userCoords = CLLocationCoordinate2D(latitude: 0, longitude: 0)
override func viewDidLoad() {
super.viewDidLoad()
//Fetch User Current Location
self.fetchUserCurrentLocation()
}
func fetchUserCurrentLocation() {
let locationFetch = FetchLocation.SharedManager
locationFetch.parentObject = self
locationFetch.startUpdatingLocation()
locationFetch.completionBlock = { [unowned self] (userCoordinates, error) in
if error != nil {
print(error?.localizedDescription ?? "")
}
if let userLocation = userCoordinates as? CLLocationCoordinate2D {
print(userLocation.latitude, userLocation.longitude)
self.userCoords = userLocation
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
联系我
Mandeep Singh
- 电子邮箱:[email protected]