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

Posted

技术标签:

【中文标题】没有在 NSObject 类 ios swift 中获取委托方法的回调【英文标题】:Not getting callbacks of delegate methods in NSObject class ios swift 【发布时间】:2017-01-31 04:49:20 【问题描述】:

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

-- 此类用于查找用户的位置,然后通过 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)")

   )*/

【问题讨论】:

你为什么要在那个方法中创建 locationManager!.delegate = nil ?一旦有位置更新,didUpdateLocation 方法将被多次调用。 我只需要第一次定位。无需更新位置,因为我想查找用户所在的国家/地区。 【参考方案1】:

我认为您的 GetCountryCode 类的实例在调用委托方法之前已被释放。创建后存储该 GetCountryCode 实例。 让我知道这是否对您有帮助。

【讨论】:

以上是关于没有在 NSObject 类 ios swift 中获取委托方法的回调的主要内容,如果未能解决你的问题,请参考以下文章

从 NSObject 派生时,Swift iOS 内存泄漏指示 XCode8

使用 Swift iOS 中的 Javascriptcore 框架将 NSobject 传递给 javascript

IOS - 啥是 Swift 字符类型的 ObjC NSObject 等价物?

swift学习第十一天:类的定义

如何在 NSObject 类中添加动态行为:Swift

在 NSObject 类中设置协议并在 UIViewController 类中调用它们