我在尝试从 api 获取坐标时遇到问题
我正在尝试创建一个包含我所有 URL 的常量类,之后我创建了另一个名为 location 的类,包括两个变量纬度和经度,我创建了一个函数来获取主控件中的纬度和经度并将其保存到位置类,所以我可以在常量类的 url 中使用它
问题是如果我尝试打印经纬度坐标
从函数中它在输出中正确显示但是当我尝试在常量类中使用时它显示 nil
我的固定类(class)
import Foundation
import Alamofire
let Base_Url = "http://api.openweathermap.org/data/2.5/weather?"
let lats = "lat="
let lons = "&lon="
let AppId = "&appid=951191ec976939570dc1aa8e0b5ed6bd"
var lat = locationClass.sharedinstance.lat
var lon = locationClass.sharedinstance.lon
let CurrentWeatherUrl = "\(Base_Url)\(lats)37.785834000000001\(lons)-122.406417\(AppId)"
let FourCastWeatherUrl = "http://api.openweathermap.org/data/2.5/forecast/daily?lat=21.5169444&lon=39.2191667&cnt=10&appid=951191ec976939570dc1aa8e0b5ed6bd"
typealias DownloadCompleted = () -> ()
位置类别
import CoreLocation
class locationClass {
static var sharedinstance = locationClass()
private init () {}
var lat: Double!
var lon: Double!
}
获取经纬度函数
func currentLocationAuth(){
if CLLocationManager.authorizationStatus() == .authorizedWhenInUse{
currentlocation = locationmanager.location
locationClass.sharedinstance.lat = currentlocation.coordinate.latitude
locationClass.sharedinstance.lon = currentlocation.coordinate.longitude
print(locationClass.sharedinstance.lat,locationClass.sharedinstance.lon)
}else{
locationmanager.requestWhenInUseAuthorization()
currentLocationAuth()
}
为什么当我尝试打印显示主控件的值时,但当我尝试在显示空的常量类中使用它时
最佳答案
我不太确定您所说的常量类是什么意思...但是某些东西,例如函数或 init 方法必须触发/初始化这些常量。如果这种情况发生在 之前,您的单例 locationClass 被加载到内存中,那么您显然会得到
nil
。所以建议是在输入 long/lat 之前简单地调用:
locationClass.sharedinstance
这样它就会初始化你的单例。
此外,在 Swift 3 中,惯例是仅使用“shared”并避免使用“sharedInstance”
关于ios - API 的位置问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43640158/