从 swift 中的另一个 class 获取位置结果

Get location results from another class in swift

如何从 (userLocation.swift) 的一个 class (GPSLocation) 获取位置结果并在文件 (target.swift) 的另一个 class 中使用它们...?

我需要国家代码、城市、经度和纬度来自:

userLocation.swift

import UIKit
import MapKit

class GPSLocation {

func getGPSLocation(completion: () -> Void) {

    let locManager = CLLocationManager()
    var currentLocation: CLLocation!
    locManager.desiredAccuracy = kCLLocationAccuracyBest

    if (CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedWhenInUse || CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedAlways) {

        currentLocation = locManager.location

        let latitude = String(format: "%.7f", currentLocation.coordinate.latitude)
        let longitude = String(format: "%.7f", currentLocation.coordinate.longitude)
        let location = CLLocation(latitude: currentLocation.coordinate.latitude, longitude: currentLocation.coordinate.longitude)

        fetchCountryAndCity(location: location) { countryCode, city in
            // debugPrint("Country:", countryCode)
            // debugPrint("City:", city)
        }
        // debugPrint("Latitude:", latitude)
        // debugPrint("Longitude:", longitude)
    }
}

//MARK: Find countryCode & City name from longitude & latitude

func fetchCountryAndCity(location: CLLocation, completion: @escaping (String, String) -> ()) {
    CLGeocoder().reverseGeocodeLocation(location) { placemarks, error in
        if let error = error {
            debugPrint(error)
        } else if let countryCode = placemarks?.first?.isoCountryCode,
            let city = placemarks?.first?.locality {
            completion(countryCode, city)
        }
    }
}
}

并将它们打印在文件中:

target.swift

import Foundation

class Post {

 fileprivate func Post() {

    func getLocation() {
        // Get user GPS location (longitude, latitude, Country Code, City)
        let getUserLocation = GPSLocation()
        getUserLocation.getGPSLocation {
            debugPrint("Country:", countryCode)
            debugPrint("City:", city)
            debugPrint("Latitude:", latitude)
            debugPrint("Longitude:", longitude)
        }
    }

  }

}

提前致谢..!!!

您可以使用委托模式来做到这一点。使用委托模式,不仅可以获取经纬度城市国家,还可以进行错误处理

首先,重写 fetchCountryAndCity 以包含错误处理程序:

func fetchCountryAndCity(location: CLLocation, completion: @escaping (String, String) -> (), errorHandler: @escaping (Error) -> ()) {
    CLGeocoder().reverseGeocodeLocation(location) { placemarks, error in
        if let error = error {
            debugPrint(error)
            errorHandler(error)
        } else if let countryCode = placemarks?.first?.isoCountryCode,
            let city = placemarks?.first?.locality {
            completion(countryCode, city)
        }
    }
}

然后,创建委托协议:

protocol GPSLocationDelegate {
    func fetchedLocationDetails(location: CLLocation, countryCode: String, city: String)
    func failedFetchingLocationDetails(error: Error)
}

GPSLocation中添加弱属性delegate:

weak var delegate: GPSLocationDelegate?

在适当的时候,调用委托方法:

public func getGPSLocation() {

    let locManager = CLLocationManager()
    var currentLocation: CLLocation!
    locManager.desiredAccuracy = kCLLocationAccuracyBest

    if (CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedWhenInUse || CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedAlways) {

        currentLocation = locManager.location

        let latitude = String(format: "%.7f", currentLocation.coordinate.latitude)
        let longitude = String(format: "%.7f", currentLocation.coordinate.longitude)
        let location = CLLocation(latitude: currentLocation.coordinate.latitude, longitude: currentLocation.coordinate.longitude)

        fetchCountryAndCity(location: location, completion: { countryCode, city in
            delegate?.fetchedLocationDetails(location: location, countryCode: countryCode, city: city)
        }) { delegate?.failedFetchingLocationDetails(error: [=13=]) }

        debugPrint("Latitude:", latitude)
        debugPrint("Longitude:", longitude)
    }
}

Postclass中,使Post符合GPSLocationDelegate:

class Post: GPSLocationDelegate {
    func fetchedLocationDetails(location: CLLocation, countryCode: String, city: String) {
         // print the stuff here
     }

     func failedFetchingLocationDetails(error: Error) {
         // handle errors
     }
}

添加一个名为 gpsLocation 的 属性:

let gpsLocation = GPSLocation()

在初始化器中,将其委托设置为 self 并调用 getLocation:

init() {
    gpsLocation.delegate = self
    gpsLocation.getLocation()
}

您的位置详细信息应该在成功获取后打印出来。

您可以在 GPSLocation class 中获取位置后定义 运行 的闭包。您可以通过两种方式实现它:

您可以在您的 GPSLocation class 中包含块代码变量,如下所示:

typealias completionHanlder = (_ lat: String, _ lng: String) -> Void
var completion: completionHanlder?

然后在 Post class 实例化 GPSLocation 之后,您可以传递如下代码块:

getUserLocation.completion = {
       // do any stuff here     
}

OR 您可以将一段代码传递给您的 getGPSLocation 函数。这是重新定义函数的方法:

func getGPSLocation(completion: (_ lat: String, _ lng: String) -> Void) {        
    let locManager = CLLocationManager()
    var currentLocation: CLLocation!
    locManager.desiredAccuracy = kCLLocationAccuracyBest

    if (CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedWhenInUse || CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedAlways) {

    currentLocation = locManager.location

    let latitude = String(format: "%.7f", currentLocation.coordinate.latitude)
    let longitude = String(format: "%.7f", currentLocation.coordinate.longitude)
    let location = CLLocation(latitude: currentLocation.coordinate.latitude, longitude: currentLocation.coordinate.longitude)

    fetchCountryAndCity(location: location, completion: { countryCode, city in
        delegate?.fetchedLocationDetails(location: location, countryCode: countryCode, city: city)
    }) { delegate?.failedFetchingLocationDetails(error: [=12=]) }

    debugPrint("Latitude:", latitude)
    debugPrint("Longitude:", longitude)

    completion(latitude, longitude)  // your block of code you passed to this function will run in this way

   }

}

这就是你的 Post class :

class Post {

func getLocation() {
    // Get user GPS location (longitude, latitude, Country Code, City)
    let getUserLocation = GPSLocation()
    getUserLocation.getGPSLocation { (lat, lng) in

        debugPrint("Latitude:", lat)
        debugPrint("Longitude:", lng)
        // HERE I NEED to PRINT longitude, latitude, Country Code, City
    }

}
}

当我在上面重写你的函数时,只要在 getGPSLocation 函数中调用完成块,你放在这里的闭包就会 运行。