如何获取已经实例化的ViewController的引用?

时间:2015-11-14 12:43:28

标签: ios swift uiviewcontroller swift2 core-location

这里快速新手。我试图让我的简单核心位置应用程序在locationManager获取坐标后自动检索数据。 我已经实现了单独的类,不让我的主视图控制器负责这里的太多任务看起来像:

import Foundation
import CoreLocation

class CoreLocationController : NSObject, CLLocationManagerDelegate {

var locationManager = CLLocationManager()

var lastCoordinates: (lat: Double, lon: Double)?

override init() {  
    super.init()
    self.locationManager.delegate = self
    self.locationManager.requestWhenInUseAuthorization()
    self.locationManager.distanceFilter  = 3000
    self.locationManager.desiredAccuracy = kCLLocationAccuracyKilometer

}

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    let location = locations.last! as CLLocation

    self.lastCoordinates = (location.coordinate.latitude, location.coordinate.longitude)
    print("didUpdateLocations:  \(location.coordinate.latitude), \(location.coordinate.longitude)")

}

func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
    print("didChangeAuthorizationStatus")

    switch status {
    case .NotDetermined:
        print(".NotDetermined")
        break

    case .AuthorizedWhenInUse:
        print(".AuthorizedWhenInUse")
        self.locationManager.startUpdatingLocation()
        break

    case .Denied:
        print(".Denied")
        break

    default:
        print("Unhandled authorization status")
        break

    }
}

func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
   }
}

当然我已经在AppDelegate.swift

中初始化了它
import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?

var coreLocationController: CoreLocationController?

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    self.coreLocationController = CoreLocationController()
    return true
}

现在,点按按钮后我的主ViewController执行retrieveWeatherForecast并传递appDelegate以获取对CoreLocationController.lastCoordinates属性的引用。我得出的结论是,为了在启动后立即获得坐标后执行retrieveWeatherForecast,最好的方法是在locationManager func(带didUpdateLocations参数的那个)中运行此方法。为了做到这一点,我需要引用ViewController运行实例来执行类似:

runningViewControlerinstance.retrieveWeatherForecast(runningViewControlerinstance.appDel)

ViewController代码:

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var currentTemperatureLabel: UILabel?
@IBOutlet weak var currentHumidityLabel: UILabel?
@IBOutlet weak var currentPrecipitationLabel: UILabel?
@IBOutlet weak var currentWeatherIcon: UIImageView?
@IBOutlet weak var currentWeatherSummary: UILabel?
@IBOutlet weak var refreshButton: UIButton?
@IBOutlet weak var activityIndicator: UIActivityIndicatorView?

let appDel = UIApplication.sharedApplication().delegate! as! AppDelegate

private var forecastAPIKey: String?

override func viewDidLoad() {
    super.viewDidLoad()

    let path = NSBundle.mainBundle().pathForResource("APIkeys", ofType: "plist")
    let dict = NSDictionary(contentsOfFile: path!)

    self.forecastAPIKey = dict!.objectForKey("forecastAPIKey") as? String

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

func retrieveWeatherForecast(appDel: AppDelegate ) {
    let currentCoordinates :(lat: Double, lon: Double) =  (appDel.coreLocationController?.lastCoordinates)!

    let forecastService = ForecastService(APIKey: forecastAPIKey!)
    forecastService.getForecast(currentCoordinates.lat, lon: currentCoordinates.lon) {
        (let currently) in

        if let currentWeather = currently {

            dispatch_async(dispatch_get_main_queue()) {

                if let temperature = currentWeather.temperature {
                    self.currentTemperatureLabel?.text = "\(temperature)º"
                }

                if let humidity = currentWeather.humidity {
                    self.currentHumidityLabel?.text = "\(humidity)%"
                }

                if let precipitation = currentWeather.precipProbability {
                    self.currentPrecipitationLabel?.text = "\(precipitation)%"
                }

                if let icon = currentWeather.icon {
                    self.currentWeatherIcon?.image = icon
                }

                if let summary = currentWeather.summary {
                    self.currentWeatherSummary?.text = summary
                }

                self.toggleRefreshAnimation(false)

            }


        }
    }
}

@IBAction func refreshWeather() {
    toggleRefreshAnimation(true)
    retrieveWeatherForecast(appDel)
}

func toggleRefreshAnimation(on: Bool) {
    refreshButton?.hidden = on
    if on {
        activityIndicator?.startAnimating()
    } else {
        activityIndicator?.stopAnimating()
    }
 }
}

我非常感谢你们迅速的社区提供的任何帮助,意见和建议,谢谢!

2 个答案:

答案 0 :(得分:0)

如果您有一个单独的类来处理位置服务(这是一个很好的设计模式)或者是app委托,那么通过NSNotification通知任何活动视图控制器的最佳方式。

通过NSNotificationCenter中的viewDidAppear在视图控制器中注册,并在viewWillDisappear中以观察者身份移除自己。有大量文档可以解释详细信息。

控制器与异步进程的松散耦合比保持对UI对象的引用更安全。

答案 1 :(得分:-1)

"当然我已经在AppDelegate.swift"中初始化了它。 为什么?没有理由在那里初始化它,是吗?在您打算使用它的地方初始化它。 viewController需要访问CoreLocationController才能使用,显示或编辑位置。因此,在那里初始化并使用它,您不必将视图控制器传递给您的位置管理员。