如何设置UIActivityIndi​​cator async

时间:2016-03-10 13:54:32

标签: ios swift

在使用Firebase的用户身份验证任务期间尝试创建旋转活动指示器时,我遇到了一个非常常见的问题

我尝试使用CGD dispatch_async,但这似乎无法解决我的问题。 这是我的代码

    @IBAction func SignMeIn(sender: AnyObject) {
    ActivityIndicator.hidden = false
    ActivityIndicator.startAnimating()



        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
            NSLog("Before login func")
            self.logIn()

            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                NSLog("After login func")
                self.ActivityIndicator.stopAnimating()
                self.ActivityIndicator.hidden = true
            })

        });
}

 func logIn(){
    myRootRef.authUser(TXT_User.text, password: TXT_Password.text,
        withCompletionBlock: { error, authData in
            if error != nil {
                NSLog(error.debugDescription)
            } else {
              NSLog("Connected !")
            }
    })


}

事情是我肯定做错了,因为在调试模式下按此顺序出现:

"Before login func"
"After login func"
"Connected !" 

而我应该

"Before login func"
"Connected !"
"After login func"

我做错了什么? 非常感谢你的帮助:)!

2 个答案:

答案 0 :(得分:2)

您的问题是您有2个异步任务  1.登录完成块  2.活动指示停止

如果您想在登录过程后停止活动指示器,您应该像这样

移动完成块中的代码
@IBAction func SignMeIn(sender: AnyObject) {
    ActivityIndicator.hidden = false
    ActivityIndicator.startAnimating()

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
        NSLog("Before login func")
        self.logIn()
    });
}

func logIn(){
myRootRef.authUser(TXT_User.text, password: TXT_Password.text,
    withCompletionBlock: { error, authData in
        if error != nil {
            NSLog(error.debugDescription)
        } else {
          NSLog("Connected !")
        }

        dispatch_async(dispatch_get_main_queue(), { () -> Void in
            NSLog("After login func")
            self.ActivityIndicator.stopAnimating()
            self.ActivityIndicator.hidden = true
        })
})
}

答案 1 :(得分:2)

问题是执行立即从logIn返回,而不是在调用完成块时返回。

要做你需要的,你必须在logIn完成处理程序中调用主队列 - 就像这样

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
        NSLog("Before login func")
        self.logIn()
 }

func logIn(){
    myRootRef.authUser(TXT_User.text, password: TXT_Password.text,
    withCompletionBlock: { error, authData in

        // success or fail, you need to stop the Activity Indicator
        dispatch_async(dispatch_get_main_queue(), { () -> Void in
                NSLog("After login func")
                self.ActivityIndicator.stopAnimating()
                self.ActivityIndicator.hidden = true
            })
        });

        if error != nil {
            NSLog(error.debugDescription)
        } else {
            NSLog("Connected !")
        }
    })
}
相关问题