我在美國使用它時遇到了應用程序崩潰。在所有其他國家,相同的代碼正在工作。崩潰是發生在行:獲取經度和緯度
let latitude = String(format: "%.7f", currentLocation.coordinate.latitude)
我實在看不出有什麼問題,特別是COS涉及美國,而不是其他縣。任何幫助將非常感激。
我UserLocation.swift看起來是這樣的:
import UIKit
import MapKit
public class GPSLocation {
static let sharedInstance = GPSLocation()
//MARK: Public variables
public var intermediateLatitude: String?
public var intermediateLongitude: String?
public var intermediateCountry: String?
public var intermediateCity: String?
public var intermediateTimeZone: String?
//MARK: Get Longitude, Country Code and City name
func getGPSLocation(completition: @escaping() -> Void) {
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let locManager = manager
var currentLocation: CLLocation!
locManager.desiredAccuracy = kCLLocationAccuracyBest
if (CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedWhenInUse || CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedAlways) {
currentLocation = locManager.location
if currentLocation != nil {
// Get longitude & latitude
let latitude = String(format: "%.7f", currentLocation.coordinate.latitude)
let longitude = String(format: "%.7f", currentLocation.coordinate.longitude)
self.intermediateLatitude = latitude
self.intermediateLongitude = longitude
// debugPrint("Latitude:",latitude)
// debugPrint("Longitude:",longitude)
// Get local time zone GMT
let localTimeZoneAbbreviation = TimeZone.current.abbreviation() ?? "" // "GMT-2"
let indexStartOfText = localTimeZoneAbbreviation.index(localTimeZoneAbbreviation.startIndex, offsetBy: 3) // 3
let timeZone = localTimeZoneAbbreviation.substring(from: indexStartOfText) // "-2"
self.intermediateTimeZone = timeZone
// debugPrint("GMT:",timeZone)
// Get Country code and City
let location = CLLocation(latitude: currentLocation.coordinate.latitude, longitude: currentLocation.coordinate.longitude)
fetchCountryAndCity(location: location) { countryCode, city in
self.intermediateCountry = countryCode
self.intermediateCity = city
// debugPrint("Country code:",countryCode)
// debugPrint("City:",city)
completition()
}
} else {
// Location is NIL
}
}
}
locManager.delegate = self // and conform protocol
locationManager.startUpdatingLocation()
}
//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)
}
}
}
}
是否已確認' locManager.location'不是'nil'? –
如果我包裹整個塊如果locManager.location不是從零//獲取經度和緯度直到Completition()結束如果聲明...? –
首先找出問題所在。如果locManager.location爲零,則問題與String(格式:...)無關。然後搜索「CLLocationManager位置爲零」,這裏已經有很多問答。 –