这里是 swift 新手。我试图让我的简单核心位置应用程序在通过 locationManager
获取坐标后自动检索数据。
我已经实现了单独的类,而不是让我的主视图 Controller 负责太多的任务,它看起来像这样:
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()
}
}
}
我将非常感谢来自 swift 社区的任何帮助、意见和建议,谢谢!
最佳答案
如果您有一个单独的类来处理位置服务(这是一个很好的设计模式)或者应用委托(delegate),通知任何事件 View Controller 的最佳方式是通过 NSNotification
。
通过 viewDidAppear
中的 NSNotificationCenter
在 View Controller 中注册,并在 viewWillDisappear
中将自己作为观察者移除。有大量文档可以解释细节。
Controller 与异步进程的这种松散耦合比保留对 UI 对象的引用要安全得多。
关于ios - 如何获取对已实例化的 ViewController 的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33708526/