ios - 暂停直到 CLLocation 不为零

标签 ios swift admob cllocationmanager

我已在应用中安装了 AdMob,并且已将其配置为可以正常工作。我遇到的一个问题是我的 CLLocationManager 在启动时有点滞后。

我将 CLLocationManager 设置为单例类,在 didFinishLoadingWithOptions 中的 AppDelegate.swift 上调用,并使用以下行:

LocationManager.sharedInstance.startUpdatingLocation()

在我的应用的初始 viewController 中,我创建了一个在 viewDidAppear 中调用的加载广告的方法。我把它放在那里,这样如果用户离开该选项卡,当他们返回该选项卡时,就会加载一个新广告。

两个问题:

1) 有没有更好的方法来处理更新 CLLocationManager 时的滞后问题?

2) 如果启用了位置服务,但由于启动滞后而 currentLocation 为零,是否可以将 currentLocation 存储在 NSUserDefaults 中并提取该位置?

func loadAd() {

    // Google Banner
    print("Google Mobile Ads SDK version: " + GADRequest.sdkVersion())

    // TODO: need to update this for production
    bannerView.adUnitID = "ca-app-pub-3940256099942544/2934735716"
    bannerView.rootViewController = self

    if CLLocationManager.locationServicesEnabled() {
        // Added this if statement to get around laggyness issue.
        if LocationManager.sharedInstance.currentLocation != nil {
            currentLocation = LocationManager.sharedInstance.currentLocation
            adRequest.setLocationWithLatitude(CGFloat((currentLocation?.coordinate.latitude)!),
                longitude: CGFloat((currentLocation?.coordinate.longitude)!),
                accuracy: CGFloat((currentLocation?.horizontalAccuracy)!))
            print("loadAd()'s current location is \(LocationManager.sharedInstance.currentLocation)")
        }
    } else {
        print("Location services not enabled")
    }

    if NSUserDefaults.standardUserDefaults().valueForKey("userGender") != nil {
        if NSUserDefaults.standardUserDefaults().stringForKey("userGender") == "male" {
            adRequest.gender = .Male
        } else {
            adRequest.gender = .Female
        }
        print("gender is set to \(adRequest.gender)")
    }

    if NSUserDefaults.standardUserDefaults().valueForKey("userBirthday") != nil {
        let birthDate = NSUserDefaults.standardUserDefaults().valueForKey("userBirthday") as! NSDate
        let now = NSDate()
        let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)
        let components = calendar?.components([.Month, .Day, .Year], fromDate: birthDate)
        let ageComponents = calendar?.components(NSCalendarUnit.Year, fromDate: birthDate, toDate: now, options: [])
        let age: NSInteger = (ageComponents?.year)!

        if age < 13 {
            adRequest.tagForChildDirectedTreatment(true)
        } else {
            adRequest.tagForChildDirectedTreatment(false)
        }

        print("The user's age is \(age)")

        adRequest.birthday = NSCalendar.currentCalendar().dateFromComponents(components!)
    }

    bannerView.loadRequest(adRequest)
}

最佳答案

我找到了一个解决方案,可以解决除初始启动之外的所有场景......

第 1 步:当设置 currentLocation 时,在我的 LocationManager 单例类中创建一个 NSUserDefault:

var currentLocation: CLLocation? {
    didSet {
        // Store coordinates as a dictionary in NSUserDefaults
        let savedLatitude: CGFloat = CGFloat((self.currentLocation?.coordinate.latitude)!)
        let savedLongitude: CGFloat = CGFloat((self.currentLocation?.coordinate.longitude)!)
        let userLocation: [String: NSNumber] = ["latitude": savedLatitude, "longitude": savedLongitude]
        NSUserDefaults.standardUserDefaults().setObject(userLocation, forKey: "savedLocation")
    }
}

第 2 步:按如下方式调整 loadAd() 方法:

    // If location services are enabled...
    if CLLocationManager.locationServicesEnabled() {
        // check if currentLocation has a value
        if LocationManager.sharedInstance.currentLocation != nil {
            currentLocation = LocationManager.sharedInstance.currentLocation
            adRequest.setLocationWithLatitude(CGFloat((currentLocation?.coordinate.latitude)!),
                longitude: CGFloat((currentLocation?.coordinate.longitude)!),
                accuracy: CGFloat((currentLocation?.horizontalAccuracy)!))
            print("loadAd()'s current location is \(LocationManager.sharedInstance.currentLocation)")
        } else {
            // if there's no value stored, tough luck
            if NSUserDefaults.standardUserDefaults().objectForKey("savedLocation") == nil {
                print("No location stored")
            } else {
                // if there IS a stored value, use it...
                print("Using stored location from NSUserDefaults")
                let userLocation = NSUserDefaults.standardUserDefaults().objectForKey("savedLocation")
                adRequest.setLocationWithLatitude(CGFloat(userLocation!.objectForKey("latitude")! as! NSNumber),
                    longitude: CGFloat(userLocation!.objectForKey("longitude")! as! NSNumber),
                    accuracy: CGFloat(3000))
                print("User location is \(userLocation)")
            }
        }
    } else {
        print("Location services not enabled")
    }

Me upon figuring it out

关于ios - 暂停直到 CLLocation 不为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34273439/

相关文章:

swift - 从数据库加载数据并将其加载到 Vapor 3 View 中的正确方法?

swift - 如何将 View TableViewCell 转换为 UIGestureView

c# - 尝试在 xamarin 表单中使用 admob 时获取 'MediationRewardedVideoAdListenerImplementor is not abstract and does not override abstract method'

ios - 快速动态创建对象和设置属性

ios - 如何将 "$123.4"之类的字符串更改为 floatValue

swift - 触摸开始时从 SKScene 中删除函数

android - 如何使 admob 与 android 版本 <=3.2 一起工作?

ios - 谷歌地图方案通过纬度和经度给出方向不起作用

ios - 您可以为容器 Controller 设置 ScrollView 插入吗?

Android:如何在应用程序中集成admob?