如何使用 swift 在 appdelegate 中获取当前位置
How to fetch current location in appdelegate using swift
您好,我正在使用 swift 开发一个应用程序,我想在应用程序启动时获取用户的当前位置,所以我在应用程序委托中编写了我的代码,我已经包含了所有功能和方法,即添加和导入的框架核心位置并更新了 plist 但我无法获取当前位置
我的应用委托中的代码:
import UIKit
import CoreLocation
import MapKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,GIDSignInDelegate,CLLocationManagerDelegate {
var locationManager:CLLocationManager!
var window: UIWindow?
var centerContainer: MMDrawerController?
private var currentCoordinate: CLLocationCoordinate2D?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
IQKeyboardManager.sharedManager().enable = true
self.locationManager = CLLocationManager()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
determineMyCurrentLocation()
var configureError: NSError?
GGLContext.sharedInstance().configureWithError(&configureError)
if (configureError != nil){
print("We have an error:\(configureError)")
}
GIDSignIn.sharedInstance().clientID = "331294109111-o54tgj4kf824pbb1q6f4tvfq215is0lt.apps.googleusercontent.com"
GIDSignIn.sharedInstance().delegate = self
return true
}
func determineMyCurrentLocation() {
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.startUpdatingLocation()
}
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
self.locationManager.stopUpdatingLocation()
let latestLocation = locations.last
let latitude = String(format: "%.4f", latestLocation!.coordinate.latitude)
let longitude = String(format: "%.4f", latestLocation!.coordinate.longitude)
print("Latitude: \(latitude)")
print("Longitude: \(longitude)")
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError)
{
print("Error \(error)")
}
func signIn(signIn: GIDSignIn!, didSignInForUser user: GIDGoogleUser!, withError error: NSError!) {
if (error == nil){
// let googleName = user.profile.name
let locValue : CLLocationCoordinate2D = currentCoordinate!
let latitude = locValue.latitude
let longitude = locValue.longitude
let userID = UIDevice.currentDevice().identifierForVendor!.UUIDString
print("users id = \(userID)")
print("userlatitude = \(latitude)")
print("userlongitude\(longitude)")
print(user.userID)
let profilePicURL = user.profile.imageURLWithDimension(200).absoluteString
print(profilePicURL)
let mainstoryboard = UIStoryboard(name: "Main", bundle:nil)
let centerViewController = mainstoryboard.instantiateViewControllerWithIdentifier("FourthViewController") as! FourthViewController
centerViewController.userid = socialMessage as String
let leftViewController = mainstoryboard.instantiateViewControllerWithIdentifier("LeftSideViewController") as! LeftSideViewController
leftViewController.ProName = user.profile.name
leftViewController.proImage = profilePicURL as String
let leftSideNav = UINavigationController(rootViewController: leftViewController)
let centerNav = UINavigationController(rootViewController: centerViewController)
self.centerContainer = MMDrawerController(centerViewController: centerNav, leftDrawerViewController: leftSideNav)
self.centerContainer!.openDrawerGestureModeMask = MMOpenDrawerGestureMode.PanningCenterView;
self.centerContainer!.closeDrawerGestureModeMask = MMCloseDrawerGestureMode.PanningCenterView;
self.window!.rootViewController = self.centerContainer
self.window!.makeKeyAndVisible()
}
}
else{
print("looks we got signin error:\(error)")
}
}
func application(application: UIApplication,
openURL url: NSURL, options: [String: AnyObject]) -> Bool {
return GIDSignIn.sharedInstance().handleURL(url,
sourceApplication: options[UIApplicationOpenURLOptionsSourceApplicationKey] as? String,
annotation: options[UIApplicationOpenURLOptionsAnnotationKey])
}
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool {
return GIDSignIn.sharedInstance().handleURL(url, sourceApplication: sourceApplication, annotation: annotation)
}
func signIn(signIn: GIDSignIn!, didDisconnectWithUser user:GIDGoogleUser!,
withError error: NSError!) {
// Perform any operations when the user disconnects from app here.
// ...
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
我还想在方法中使用当前经纬度:
func signIn(signIn: GIDSignIn!, didSignInForUser user: GIDGoogleUser!, withError error: NSError!) {
here i want to use lat and long
}
// Just call setupLocationManager() in didFinishLaunchingWithOption.
func setupLocationManager(){
locationManager = CLLocationManager()
locationManager?.delegate = self
self.locationManager?.requestAlwaysAuthorization()
locationManager?.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager?.startUpdatingLocation()
}
// Below method will provide you current location.
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if currentLocation == nil {
currentLocation = locations.last
locationManager?.stopMonitoringSignificantLocationChanges()
let locationValue:CLLocationCoordinate2D = manager.location!.coordinate
print("locations = \(locationValue)")
locationManager?.stopUpdatingLocation()
}
}
// Below Mehtod will print error if not able to update location.
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Error")
}
通过下面的代码可以得到位置的名称和经纬度
extension AppDelegate : CLLocationManagerDelegate
{
func geocode(latitude: Double, longitude: Double, completion: @escaping (CLPlacemark?, Error?) -> ()) {
CLGeocoder().reverseGeocodeLocation(CLLocation(latitude: latitude, longitude: longitude)) { completion([=10=]?.first, ) }
}
// Below Mehtod will print error if not able to update location.
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Error Location")
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
//Access the last object from locations to get perfect current location
if let location = locations.last {
let myLocation = CLLocationCoordinate2DMake(location.coordinate.latitude,location.coordinate.longitude)
geocode(latitude: myLocation.latitude, longitude: myLocation.longitude) { placemark, error in
guard let placemark = placemark, error == nil else { return }
// you should always update your UI in the main thread
DispatchQueue.main.async {
// update UI here
print("address1:", placemark.thoroughfare ?? "")
print("address2:", placemark.subThoroughfare ?? "")
print("city:", placemark.locality ?? "")
print("state:", placemark.administrativeArea ?? "")
print("zip code:", placemark.postalCode ?? "")
print("country:", placemark.country ?? "")
}
}
}
manager.stopUpdatingLocation()
}
}
您好,我正在使用 swift 开发一个应用程序,我想在应用程序启动时获取用户的当前位置,所以我在应用程序委托中编写了我的代码,我已经包含了所有功能和方法,即添加和导入的框架核心位置并更新了 plist 但我无法获取当前位置
我的应用委托中的代码:
import UIKit
import CoreLocation
import MapKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,GIDSignInDelegate,CLLocationManagerDelegate {
var locationManager:CLLocationManager!
var window: UIWindow?
var centerContainer: MMDrawerController?
private var currentCoordinate: CLLocationCoordinate2D?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
IQKeyboardManager.sharedManager().enable = true
self.locationManager = CLLocationManager()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
determineMyCurrentLocation()
var configureError: NSError?
GGLContext.sharedInstance().configureWithError(&configureError)
if (configureError != nil){
print("We have an error:\(configureError)")
}
GIDSignIn.sharedInstance().clientID = "331294109111-o54tgj4kf824pbb1q6f4tvfq215is0lt.apps.googleusercontent.com"
GIDSignIn.sharedInstance().delegate = self
return true
}
func determineMyCurrentLocation() {
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.startUpdatingLocation()
}
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
self.locationManager.stopUpdatingLocation()
let latestLocation = locations.last
let latitude = String(format: "%.4f", latestLocation!.coordinate.latitude)
let longitude = String(format: "%.4f", latestLocation!.coordinate.longitude)
print("Latitude: \(latitude)")
print("Longitude: \(longitude)")
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError)
{
print("Error \(error)")
}
func signIn(signIn: GIDSignIn!, didSignInForUser user: GIDGoogleUser!, withError error: NSError!) {
if (error == nil){
// let googleName = user.profile.name
let locValue : CLLocationCoordinate2D = currentCoordinate!
let latitude = locValue.latitude
let longitude = locValue.longitude
let userID = UIDevice.currentDevice().identifierForVendor!.UUIDString
print("users id = \(userID)")
print("userlatitude = \(latitude)")
print("userlongitude\(longitude)")
print(user.userID)
let profilePicURL = user.profile.imageURLWithDimension(200).absoluteString
print(profilePicURL)
let mainstoryboard = UIStoryboard(name: "Main", bundle:nil)
let centerViewController = mainstoryboard.instantiateViewControllerWithIdentifier("FourthViewController") as! FourthViewController
centerViewController.userid = socialMessage as String
let leftViewController = mainstoryboard.instantiateViewControllerWithIdentifier("LeftSideViewController") as! LeftSideViewController
leftViewController.ProName = user.profile.name
leftViewController.proImage = profilePicURL as String
let leftSideNav = UINavigationController(rootViewController: leftViewController)
let centerNav = UINavigationController(rootViewController: centerViewController)
self.centerContainer = MMDrawerController(centerViewController: centerNav, leftDrawerViewController: leftSideNav)
self.centerContainer!.openDrawerGestureModeMask = MMOpenDrawerGestureMode.PanningCenterView;
self.centerContainer!.closeDrawerGestureModeMask = MMCloseDrawerGestureMode.PanningCenterView;
self.window!.rootViewController = self.centerContainer
self.window!.makeKeyAndVisible()
}
}
else{
print("looks we got signin error:\(error)")
}
}
func application(application: UIApplication,
openURL url: NSURL, options: [String: AnyObject]) -> Bool {
return GIDSignIn.sharedInstance().handleURL(url,
sourceApplication: options[UIApplicationOpenURLOptionsSourceApplicationKey] as? String,
annotation: options[UIApplicationOpenURLOptionsAnnotationKey])
}
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool {
return GIDSignIn.sharedInstance().handleURL(url, sourceApplication: sourceApplication, annotation: annotation)
}
func signIn(signIn: GIDSignIn!, didDisconnectWithUser user:GIDGoogleUser!,
withError error: NSError!) {
// Perform any operations when the user disconnects from app here.
// ...
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
我还想在方法中使用当前经纬度:
func signIn(signIn: GIDSignIn!, didSignInForUser user: GIDGoogleUser!, withError error: NSError!) {
here i want to use lat and long
}
// Just call setupLocationManager() in didFinishLaunchingWithOption.
func setupLocationManager(){
locationManager = CLLocationManager()
locationManager?.delegate = self
self.locationManager?.requestAlwaysAuthorization()
locationManager?.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager?.startUpdatingLocation()
}
// Below method will provide you current location.
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if currentLocation == nil {
currentLocation = locations.last
locationManager?.stopMonitoringSignificantLocationChanges()
let locationValue:CLLocationCoordinate2D = manager.location!.coordinate
print("locations = \(locationValue)")
locationManager?.stopUpdatingLocation()
}
}
// Below Mehtod will print error if not able to update location.
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Error")
}
通过下面的代码可以得到位置的名称和经纬度
extension AppDelegate : CLLocationManagerDelegate
{
func geocode(latitude: Double, longitude: Double, completion: @escaping (CLPlacemark?, Error?) -> ()) {
CLGeocoder().reverseGeocodeLocation(CLLocation(latitude: latitude, longitude: longitude)) { completion([=10=]?.first, ) }
}
// Below Mehtod will print error if not able to update location.
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Error Location")
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
//Access the last object from locations to get perfect current location
if let location = locations.last {
let myLocation = CLLocationCoordinate2DMake(location.coordinate.latitude,location.coordinate.longitude)
geocode(latitude: myLocation.latitude, longitude: myLocation.longitude) { placemark, error in
guard let placemark = placemark, error == nil else { return }
// you should always update your UI in the main thread
DispatchQueue.main.async {
// update UI here
print("address1:", placemark.thoroughfare ?? "")
print("address2:", placemark.subThoroughfare ?? "")
print("city:", placemark.locality ?? "")
print("state:", placemark.administrativeArea ?? "")
print("zip code:", placemark.postalCode ?? "")
print("country:", placemark.country ?? "")
}
}
}
manager.stopUpdatingLocation()
}
}