appdelegate中的计时器导致崩溃

时间:2018-08-06 15:21:37

标签: ios swift crash

 var timer:Timer? = Timer()
 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
if (launchOptions == nil) {

                heartbeat()
                timer = Timer.scheduledTimer(timeInterval: 60, target: self, selector: #selector(AppDelegate.heartbeat), userInfo: nil, repeats: true)

这是心跳功能

@objc func heartbeat() {
        let userID = TegKeychain.get("userID")!
        let parameters: Parameters = ["userID": userID]
        Alamofire.request("https://example.com", method: .post, parameters: parameters).validate().responseJSON { response in
            switch response.result {
            case .success:
                if let json = response.result.value {
                    var success = 0
                    if let dictJSON = json as? [String: AnyObject] {
                        if let successInteger = dictJSON["success"] as? Int {
                            success = successInteger
                            if success == 1
                            {
                             print("HEARTBEAT")
                            }
                        }
                    }
                }
            case .failure(_):
                return
            }
        }
    }

我在这里使计时器无效

func applicationWillResignActive(_ application: UIApplication) {
            timer?.invalidate()
            timer = nil
        }



func applicationWillTerminate(_ application: UIApplication) {

        timer?.invalidate()
        timer = nil
       }

func applicationDidEnterBackground(_ application: UIApplication) {
        timer?.invalidate()
        timer = nil
        }

我在这里重置了

func applicationWillEnterForeground(_ application: UIApplication) {
            heartbeat()
            timer = Timer.scheduledTimer(timeInterval: 60, target: self, selector: #selector(AppDelegate.heartbeat), userInfo: nil, repeats: true)

但是我收到了很多崩溃报告

Crashed: com.apple.main-thread
0  Jemiyet                        0x100a6ec0c specialized AppDelegate.heartbeat() -> () (AppDelegate.swift:479)
1  Jemiyet                        0x100a718e4 specialized AppDelegate.application(UIApplication, didFinishLaunchingWithOptions : [UIApplicationLaunchOptionsKey : Any]?) -> Bool (AppDelegate.swift:205)
2  Jemiyet                        0x100a6c844 @objc AppDelegate.application(UIApplication, didFinishLaunchingWithOptions : [UIApplicationLaunchOptionsKey : Any]?) -> Bool (AppDelegate.swift)
3  UIKit                          0x18e9d9dbc -[UIApplication _handleDelegateCallbacksWithOptions:isSuspended:restoreState:] + 408
4  UIKit                          0x18e9d91c4 -[UIApplication _callInitializationDelegatesForMainScene:transitionContext:] + 3484
5  UIKit                          0x18e9a65e0 -[UIApplication _runWithMainScene:transitionContext:completion:] + 1680
6  UIKit                          0x18efd6b1c __111-[__UICanvasLifecycleMonitor_Compatability _scheduleFirstCommitForScene:transition:firstActivation:completion:]_block_invoke + 784
7  UIKit                          0x18e9a5dd0 +[_UICanvas _enqueuePostSettingUpdateTransactionBlock:] + 160
8  UIKit                          0x18e9a5c6c -[__UICanvasLifecycleMonitor_Compatability _scheduleFirstCommitForScene:transition:firstActivation:completion:] + 240
9  UIKit                          0x18e9a4afc -[__UICanvasLifecycleMonitor_Compatability activateEventsOnly:withContext:completion:] + 724
10 UIKit                          0x18f63a84c __82-[_UIApplicationCanvas _transitionLifecycleStateWithTransitionContext:completion:]_block_invoke + 296
11 UIKit                          0x18e9a41ec -[_UIApplicationCanvas _transitionLifecycleStateWithTransitionContext:completion:] + 432
12 UIKit                          0x18f41fac8 __125-[_UICanvasLifecycleSettingsDiffAction performActionsForCanvas:withUpdatedScene:settingsDiff:fromSettings:transitionContext:]_block_invoke + 220
13 UIKit                          0x18f56dbf8 _performActionsWithDelayForTransitionContext + 112
14 UIKit                          0x18e9a3c0c -[_UICanvasLifecycleSettingsDiffAction performActionsForCanvas:withUpdatedScene:settingsDiff:fromSettings:transitionContext:] + 248
15 UIKit                          0x18e9a35a8 -[_UICanvas scene:didUpdateWithDiff:transitionContext:completion:] + 368
16 UIKit                          0x18e9a05e0 -[UIApplication workspace:didCreateScene:withTransitionContext:completion:] + 540
17 UIKit                          0x18e9a0330 -[UIApplicationSceneClientAgent scene:didInitializeWithEvent:completion:] + 364
18 FrontBoardServices             0x1875cc470 -[FBSSceneImpl _didCreateWithTransitionContext:completion:] + 364
19 FrontBoardServices             0x1875d4d6c __56-[FBSWorkspace client:handleCreateScene:withCompletion:]_block_invoke_2 + 224
20 libdispatch.dylib              0x1846bca60 _dispatch_client_callout + 16
21 libdispatch.dylib              0x1846c4170 _dispatch_block_invoke_direct$VARIANT$mp + 224
22 FrontBoardServices             0x187600878 __FBSSERIALQUEUE_IS_CALLING_OUT_TO_A_BLOCK__ + 36
23 FrontBoardServices             0x18760051c -[FBSSerialQueue _performNext] + 404
24 FrontBoardServices             0x187600ab8 -[FBSSerialQueue _performNextFromRunLoopSource] + 56
25 CoreFoundation                 0x184d73404 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 24
26 CoreFoundation                 0x184d72c2c __CFRunLoopDoSources0 + 276
27 CoreFoundation                 0x184d7079c __CFRunLoopRun + 1204
28 CoreFoundation                 0x184c90da8 CFRunLoopRunSpecific + 552
29 GraphicsServices               0x186c76020 GSEventRunModal + 100
30 UIKit                          0x18ecb0758 UIApplicationMain + 236
31 Jemiyet                        0x100a090c4 main (InboxInterests.swift:28)
32 libdyld.dylib                  0x184721fc0 start + 4

2 个答案:

答案 0 :(得分:1)

我不认为您的应用因计时器而崩溃,您只是在didFinishLaunchingWithOptions :中安排它,但是您的应用在didFinishLaunchingWithOptions :内部崩溃,因此我认为您对hearbeat()的调用导致了崩溃,很可能您有不应该是nil的东西。

也许在启动时let parameters: Parameters = ["userID": userID] userID为零,因此它崩溃了...

答案 1 :(得分:0)

我想知道您是否正在使用心跳功能,因为您要在计时器返回后启动计时器,而不是在HTTP请求返回时启动计时器。

也许可以在您的心跳功能中尝试一下:

 if success == 1
    {
    print("HEARTBEAT")
    // start your timer here
    }