Reputation: 45
I'm facing an issue while trying to get my coordinate from api
I'm trying to create a constant class that includes all my URL's after that I create another class called location includes two variables latitude and longitude and i create a function to get the lat and long in the main control and save it into location class so i can use it in the url in the constant class
The problem is if I try to print the coordinate the latitude and longitude
from the function it appears correctly in the output but when I try to use in the constant class it's showing nil
my constant 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 = () -> ()
location class
import CoreLocation
class locationClass {
static var sharedinstance = locationClass()
private init () {}
var lat: Double!
var lon: Double!
}
the function that getting the latitude and longitude
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()
}
why when I try to print the value from main control showing but when I try to use it in constant class showing empty
Upvotes: 0
Views: 54
Reputation: 36287
I'm not so sure what you mean by a constant class...but something ie a function or an init method has to trigger/initialize those constants. If that happens before your singleton locationClass is loaded into the memory then obviously you'll get nil
.
So the suggestion is to simply call: locationClass.sharedinstance
before feeding your long/lat so it would initialize your singleton.
Additionally in Swift 3, the convention is to simply use 'shared' and avoid using 'sharedInstance'
Upvotes: 1