Reputation: 2998
I am using the CoreLocation
framework to get the user's location when they open up my app. I use this function:
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
var locValue:CLLocationCoordinate2D = manager.location!.coordinate
print("locations = \(locValue.latitude) \(locValue.longitude)")
}
to get the user's longitude and latitude position, and I can see them by printing them to the logs. This works fine.
elsewhere in my app (but in the same viewController.swift
file) I have code that uses the OpenWeatherMap API, and I have a string that contains the url for this, which return JSON.
In my viewDidLoad
, I use:
getWeatherData("http://api.openweathermap.org/data/2.5/weather?lat=XXXXXX&lon=XXXXXX&appid=(MY-APP-ID)")
I need to place the Long and Lat values that I've acquired in the locationManager
function, into this string, which I know I can do by "\()"
within the url string.
My problem is, I can currently only use these values inside the locationManager
function. How can I store them in a value outside of this function, so I can add them into my URL string?
Thanks
Upvotes: 0
Views: 690
Reputation: 862
Hope this answers your question.
import UIKit
import MapKit
class myClass {
var userLocation: CLLocationCoordinate2D? // The user location as an Optional stored as a var in class "myClass".
// !!! This can be accessed everywhere within the class "myClass" (and deeper)
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let locValue:CLLocationCoordinate2D = manager.location!.coordinate // Change it from var to let since it's only read not writen
// !!! This can be accessed everywhere within the func "locationManager" (and deeper)
userLocation = locValue // !!! Store it if necessary
// Why would you call this in viewDidLoad? I doubt the user location will be available at this point (but it might). You can move this anywhere if you want
// note the "\(name)" this will turn the var name into a string
// if != nil not necessary here since it cannot be nil but still added it regardless
// Maybe you want to add a check so this only gets called on the first location update. It depends on what you need it for.
if userLocation != nil {
getWeatherData("http://api.openweathermap.org/data/2.5/weather?lat=\(userLocation!.latitude)&lon=\(userLocation!.latitude)&appid=(MY-APP-ID)") // Why would you call this in viewDidLoad? I doubt user doubt the user location will be available at this point (but it might)
}
else {
print("Error: User not Located (yet)")
}
}
}
Upvotes: 3