来自 API 的位置问题

Location issue from API

我在尝试从 api

获取坐标时遇到问题

我正在尝试创建一个包含我所有 URL 的常量 class 然后我创建另一个 class 称为位置包括两个变量纬度和经度并且我创建一个在主控件中获取纬度和经度并将其保存到位置 class 的函数,这样我就可以在常量 class

中的 url 中使用它

问题是如果我尝试打印经纬度坐标 从函数中它在输出中正确显示但是当我尝试在常量 class 中使用时它显示 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 = () -> ()

位置class

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()
    }

为什么当我尝试从显示的主控件打印值时,但当我尝试在常量 class 中使用它时显示空

  1. 我不太确定常量 class 是什么意思...但是某些东西,即函数或 init 方法必须 trigger/initialize 这些常量。如果发生这种情况 之前你的单例 locationClass 被加载到内存中那么显然你会得到 nil.

  2. 所以建议在喂 long/lat 之前简单地调用:locationClass.sharedinstance 这样它就会初始化你的单例。

另外在Swift 3中,约定是简单地使用'shared'并避免使用'sharedInstance'