gpt4 book ai didi

ios - 如何使用 swift 在应用程序中调用一次计时器?

转载 作者:可可西里 更新时间:2023-11-01 00:02:57 26 4
gpt4 key购买 nike

大家好,我在我的应用程序中使用 swift 2 开发一个应用程序,我每 x 分钟更新一次当前位置,所以我使用 NSTimer 能够更新位置,一切正常。在我的应用程序(第一个 View Controller )中,当用户成功登录时在(第二个 View Controller )中并移动到第二个 View Controller 我编写了使用 NSTimer 更新位置的函数它工作正常但是当用户移动到第三个 View Controller 并返回到第二个 View Controller 时它再次开始更新位置所以我不能停止计时器两次它使计时器无效一次只有另一个即使在用户注销后也会继续更新位置。所以请有人帮我解决这个问题。

我的第二个 View Controller :

class secondviewcontroller:UIViewController{

在 View 中加载方法:

  var appDelegate:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.timer = NSTimer.scheduledTimerWithTimeInterval(10.0, target: self, selector: #selector(timeToMoveOn), userInfo: nil, repeats: true)

//i declared var timer:nstimer! in appdelegate.swift and i performed some function using nstimer

我的第三个 View Controller :

我为注销代码创建了一个按钮操作是:

  var appDelegate:AppDelegate = (UIApplication.sharedApplication().delegate as?
AppDelegate)!
appDelegate.timer.invalidate()

提前致谢

大家好,谢谢大家的支持,我找到了问题的答案

我只是根据我的项目以两种不同的方法保留了 timer.invalidate()

最佳答案

我建议这样做:

这个单例包装位置。

抱歉,对于 swift3 但它看起来像这样:

class LM: NSObject, CLLocationManagerDelegate {
//MARK: Public Variable

var lat = 0.0
var lon = 0.0
var CAST = "location_cast"
public static let i : LM = {
let instance = LM()
return instance
}()

//MARK: Local Variable

fileprivate var locationManager: CLLocationManager?

//MARK: Init
public override init() {
super.init()
locationManager = CLLocationManager()
locationManager?.delegate = self
}
internal func start() {
locationManager?.startUpdatingLocation()
}
internal func stop() {
locationManager?.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
//code
print("\(error)")
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
//code
// print("\(locations)")
if let loc = locations.last {
//simple store to retrieve it later
lat = loc.coordinate.latitude
lon = loc.coordinate.longitude


//cast here notification
NotificationCenter.default.post(name: NSNotification.Name(rawValue: CAST), object: ["lat": lat, "lon": lon])
}

}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
switch status {
case .notDetermined:
manager.requestAlwaysAuthorization()
break
case .authorizedWhenInUse:
manager.startUpdatingLocation()
break
case .authorizedAlways:
manager.startUpdatingLocation()
break
case .restricted:
// restricted by e.g. parental controls. User can't enable Location Services
break
case .denied:
// user denied your app access to Location Services, but can grant access from Settings.app
break
}
}
}

启动和停止这个 locationmanager 使用这个:

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
//...
var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
// Override point for customization after application launch.
_ = LM.i
return true
}

func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.

LM.i.stop()
}

func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.

LM.i.start()
}
}

您可以在 AppDelegate 中添加您的自定义计时器,每 1 秒转换一次变量

let CASTTOVIEWCONTROLLER = "CASTTOVIEWCONTROLLER"
NotificationCenter.default.post(name: NSNotification.Name(rawValue: CASTTOVIEWCONTROLLER), object: ["lat": LM.i.lat, "lon": LM.i.lon])

甚至简单

 let CASTTOVIEWCONTROLLER_PING = "CASTTOVIEWCONTROLLER_PING"
NotificationCenter.default.post(name: NSNotification.Name(rawValue: CASTTOVIEWCONTROLLER), object: nil)

要从转换的值中捕获新数据,请使用如下内容:

https://stackoverflow.com/a/38615219/1979882

如果您不管理 .start().stop() 如果您按下“主页”按钮,iOS 将在几分钟后启动您的后台计时器应用程序.

关于ios - 如何使用 swift 在应用程序中调用一次计时器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40521710/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com