没有在NSObject类ios swift中获得委托方法的回调

时间:2017-01-31 04:49:20

标签: ios iphone swift swift2

- 类的用法在类文件的顶部作为注释代码提到。

- 此类用于查找用户的位置,然后使用Google的API获取位置国家/地区。

- 没有在locationManager的委托方法中获得位置回调,例如" didUpdateLocations"即使我写了#34; locationManager.delegate = self"。

- 请检查以下代码。我需要帮助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)")

   })*/

1 个答案:

答案 0 :(得分:1)

我认为您的类GetCountryCode的实例在调用委托方法之前被释放。在创建GetCountryCode之后存储该实例。 如果这有助于你,请告诉我。