如何使用swift在应用程序中调用一次定时器?
大家好我正在开发一个应用程序在我的应用程序中使用swift 2更新当前位置为每x分钟,所以我使用NSTimer能够更新位置和一切工作正常。在我的应用程序(第一视图控制器)当用户成功登录并移动到第二个视图控制器(第二视图控制器)我写了更新位置功能使用NSTimer它工作正常,但当用户移动到第三个视图控制器并返回到第二个视图控制器它再次开始更新位置,所以我无法停止定时器两次使定时器失效一次只有其他一个持续更新位置,甚至在用户注销之后。所以请有人帮我解决这个问题。如何使用swift在应用程序中调用一次定时器?
我的第二视图控制器:
class secondviewcontroller:UIViewController{
鉴于
做负载方法:
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
我的第三视图控制器:
我创建了一个按钮动作为注销代码是:
var appDelegate:AppDelegate = (UIApplication.sharedApplication().delegate as?
AppDelegate)!
appDelegate.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将踢几分钟,你的背景计时器每个应用程序的将按'主页'按钮。
而不是从推找到了答案,我的问题
我只是不停地timer.invalidate()两种不同的方法第三视图控制器到第二视图控制器。您可以弹出到第二个视图控制器。那么你的viewDidLoad将不会调用。
当用户登录,然后用户将这个程序应该更新位置
var timer:NSTimer//global variable
在secondViewController的viewDidLoad方法在其他视图控制器上执行某些操作,以便他们需要处理第二个视图控制器....我不能在用户注销之前停止计时器 – antonyraja
你能解释一下更多吗? – User511
正在为驾驶员开发一个应用程序,当用户成功登录后,它会移动到其他控制器,它应该每x分钟更新用户(驾驶员)的当前位置,以便乘客可以轻松地通知驾驶员在确切的位置。在该第二视图控制器(成功登录后)有一个控制器,显示即将在该控制器中的驱动程序的行程,只有我编写了更新位置的功能,并且有许多控制器,如当前行程和完成行程 – antonyraja
当我看到您的代码时,请在您的AppDelegate类中添加一个标志或Bool变量。现在,当您从第一个屏幕进入第二个屏幕时,该标志将被启用,并且当您想要导航到第三个屏幕时将false设置为标志,并且通过检查标志是否为真,您的计时器将以真实条件运行。现在,当你再次在第二屏幕从第三来临,如果计时器的情况下再然后出现PLZ参考以下链接: NSTimer Not Stopping When Invalidated
希望此举能帮助你
感谢您的快速回复..我会检查出来这个 – antonyraja
timer的目标是第二个viewController,第二个viewController拥有这个对象,AppDelegate只对这个对象引用,AppDelegate不能释放这个对象并且只有secondViewController可以。除非secondViewController是破坏
这样:
timer = NSTimer.scheduledTimerWithTimeInterval(10.0, target: self, selector: #selector(timeToMoveOn), userInfo: nil, repeats: true)
在thirdViewController
:
let timer = (secondViewControllers object)'s timer
timer.invalidate()
你会明白我的问题吗? – antonyraja
一切工作正常......但是当用户再次移动到第二个视图控制器时,它再次调用该函数并继续更新位置......如果用户移动两次或三次到该控制器,我只能使计时器失效一次...其他事情不断更新 – antonyraja
会在后台执行应用程序吗? – antonyraja
@antonyraja,已更新 – Vyacheslav
我在三个视图控制器中获取当前位置。第一个是登录,因为我必须检查用户lat第二个是每x分钟更新当前位置,第三个是我使用mapview .. .will你的代码会导致任何问题到其他视图控制器的位置或它将停止定时器在特定的视图控制器.......感谢您的支持 – antonyraja