如何從(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