如何从(userLocation.swift)中的一个类(GPSLocation)获取位置结果并将其用于文件(target.swift)中的另一个类中。从swift获取其他类的位置结果
我需要COUNTRYCODE,城市,经度和纬度:
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)
}
}
}
}
预先感谢您.. !!!
创建共享实例/单身? – Larme
当你调用'getGPSLocation'时,你不打印你想要的东西吗? – Sweeper
将闭包传递给'getGPSLocation'并从'fetchCountryAndCity'完成处理函数中调用它 – Paulw11