未在NSObject类ios swift中获取委托方法的回调

wj8zmpe1  于 2023-05-27  发布在  Swift
关注(0)|答案(1)|浏览(138)

--类的用法在类文件的顶部作为注解代码提到。
--这个类用于查找用户的位置,然后使用Google的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)")

   })*/
4urapxun

4urapxun1#

我认为你的类GetCountryCode的示例在调用委托方法之前被释放了。在创建GetCountryCode示例后存储该示例。

相关问题