2017-01-31 1 views
0

- 클래스 사용은 주석 처리 된 코드로 클래스 파일의 맨 위에 언급되어있다.NSObject 클래스의 델리게이트 메소드의 콜백을받지 못한다.

-이 클래스는 사용자의 위치를 ​​찾는 데 사용되며 그 후에 국가의 위치는 Google의 API로 가져옵니다.

- "didUpdateLocations"와 같은 locationManager의 대리자 메소드에서 "locationManager.delegate = self"를 쓴 경우에도 위치 콜백을받지 못했습니다.

- 아래 코드를 확인하십시오. 나는 젖은 잘못을 알아 내는데 도움이 필요합니다. 이러한 유형의 구성이 가능하지 않은 경우 대체 코드 블록을 아래 코드로 대체하여 제안하십시오.

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 = nil입니까? didUpdateLocation 메소드는 위치 업데이트가있는 즉시 여러 번 호출됩니다. –

+0

처음으로 위치 정보가 필요합니다. 사용자 위치의 국가를 찾고 싶기 때문에 위치 업데이트가 필요 없습니다. –

답변

0

나는 대리자 메서드를 호출하기 전에 클래스 GetCountryCode의 인스턴스가 할당 해제됩니다 생각합니다. GetCountryCode 인스턴스를 만든 후에 저장하십시오. 이것이 도움이되었는지 알려주세요.

관련 문제