Reputation: 170
-- Usage of class is mentioned in top of class file as a commented code.
-- This class is used to find user's location and after that from location country is fetched with google's API.
-- Did not get location callbacks in locationManager's delegate methods like "didUpdateLocations" even if i wrote "locationManager.delegate = self".
-- Please check below code. I need help guyz to find out what wet wrong. If this type of configuration not possible then please suggest me alternative code block to replace below code.
import UIKit
import CoreLocation
class GetCountryCode: NSObject, CLLocationManagerDelegate {
// Usage of class
/*let getCountryeCode = GetCountryCode()
getCountryeCode.createLocationRequest({ (response) -> Void in
print("Response:\(response)")
})*/
typealias CompletionHandler = (countryCode:String) -> Void
var completionHandler: CompletionHandler?
private var locationManager: CLLocationManager?
func createLocationRequest(completionHandler: CompletionHandler){
self.completionHandler = completionHandler
locationManager = CLLocationManager()
locationManager!.delegate = self
locationManager!.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager!.distanceFilter = 10
locationManager!.requestWhenInUseAuthorization()
locationManager!.startUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
print("Error while updating location " + error.localizedDescription)
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let locationArray = locations as NSArray
let locationObj = locationArray.lastObject as! CLLocation
locationManager!.stopUpdatingLocation()
locationManager!.stopMonitoringSignificantLocationChanges()
executeProcess(self.completionHandler!, location: locationObj)
locationManager!.delegate = nil
}
func executeProcess(completionHandler: CompletionHandler, location:CLLocation) {
let latitude = location.coordinate.latitude.description
let longitude = location.coordinate.longitude.description
let request = NSMutableURLRequest(URL: NSURL(string: CommonUtils.google_geoCode_url + "?latlng=\(latitude),\(longitude)&key=\(CommonUtils.google_server_key)")!)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "GET"
print("CountryCodeURL:\(request.URL)")
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
if(data==nil){
// self.buildErrorOnSignIn()
}else{
self.parseResponse(data!, completionHandler: completionHandler)
}
})
task.resume()
}
func parseResponse(data:NSData, completionHandler: CompletionHandler){
let dict: NSDictionary!=(try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers)) as! NSDictionary
let status_str=dict.valueForKey("status") as! NSString
if(status_str != "OK" || dict.valueForKey("results") == nil){
dispatch_async(dispatch_get_main_queue()) {
completionHandler(countryCode: "")
}
return;
}
let results_arr = dict.valueForKey("results") as! NSArray
if(results_arr.count > 0){
var countryCode_temp = ""
var isCountryCodeMatch = false
for i in 0 ..< results_arr.count{
let addressComponents = results_arr[i].valueForKey("address_components")
if(addressComponents != nil){
let addressComponents_arr = addressComponents as! NSArray
for j in 0 ..< addressComponents_arr.count {
let types_arr = addressComponents_arr[j].valueForKey("types") as! NSArray
for k in 0 ..< types_arr.count {
let type = String(types_arr.objectAtIndex(k))
if(type == "country"){
countryCode_temp = String(addressComponents_arr[j].valueForKey("short_name")!)
isCountryCodeMatch = true
break
}
}
if(isCountryCodeMatch == true){
break
}
}
if(isCountryCodeMatch == true){
break
}
}
}
print("countryCode_temp::\(countryCode_temp)")
dispatch_async(dispatch_get_main_queue()) {
completionHandler(countryCode: countryCode_temp)
}
}else{
dispatch_async(dispatch_get_main_queue()) {
completionHandler(countryCode: "")
}
}
}
}
// Usage of class
/*let getCountryeCode = GetCountryCode()
getCountryeCode.createLocationRequest({ (response) -> Void in
print("Response:\(response)")
})*/
Upvotes: 1
Views: 443
Reputation: 771
I think instance of your class GetCountryCode is deallocated before delegate method called. Store that instance of GetCountryCode after you created it.
Upvotes: 2