代码之家  ›  专栏  ›  技术社区  ›  Utku Dalmaz

appdelegate中的计时器导致崩溃

  •  0
  • Utku Dalmaz  · 技术社区  · 7 年前
     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 回复  |  直到 7 年前
        1
  •  1
  •   Ladislav    7 年前

    我不认为你的应用程序因为计时器而崩溃,你只是在计划它 didFinishLaunchingWithOptions : 但你的应用程序在 DidFinishLaunching选项: 所以我想你的电话 hearbeat() 是导致坠机的原因,很可能你的东西不应该是零就是零。

    也许在发射的时候 let parameters: Parameters = ["userID": userID] userID 是零,所以它崩溃了。。。

        2
  •  0
  •   Stephen O'Connor    7 年前

    我想知道您是否正在对heartbeat函数进行竞争,因为您是在它返回后启动计时器的,而不是在http请求返回时启动计时器。

    也许在心跳函数中试试这个:

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