2017-01-31 34 views
0

- 类的使用在类文件的顶部作为注释代码提及。未获得NSObject类中的委托方法的回调ios swift

- 此类用于查找用户的位置,然后从位置国家获取谷歌的API。

- 即使我写了“locationManager.delegate = self”,没有在locationManager的委托方法(如“didUpdateLocations”)中获取位置回调。

- 请检查以下代码。我需要帮助guyz来找出什么是错误的。如果这种类型的配置不可能,那么请建议我使用替代代码块替换下面的代码。

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)") 

    })*/ 
+0

为什么你做的LocationManager!.delegate =零该方法?一旦有位置更新,didUpdateLocation方法将被多次调用。 –

+0

我只需要位置第一次。没有必要因为我的位置更新要找到用户所在位置的国家。 –

回答

0

我觉得你的类GetCountryCode的情况下被释放所谓的委托方法之前。在创建GetCountryCode后存储该实例。 让我知道这是否帮助你。