为什么我需要使用dispatch_async我想我在同一个线程上

时间:2015-07-17 02:52:47

标签: ios multithreading uiactivityindicatorview

我在IOS中使用swift登录页面。当我单击SignIn按钮时,我启动登录过程,该过程在完成时调用具有委托回调的函数。这很好,我的活动指示器开始旋转。问题是,当我得到我的委托回调并且我在指示器上调用stopanimating()时它会在大约6秒后停止。如果我添加dispatch_async,它将立即停止动画。这让我相信我没有在同一个线程上运行,但我不知道这是怎么回事。

编辑:看起来当我在我的Rest函数session.dataTaskWithRequest()中调用时,返回的代码块不在主线程上,所以当我调用委托并返回主代码时,它是不是主线程?它是否正确?我无法找到可以解释这一点的文档。

class Login_ViewController: UIViewController, RestServiceDelegate {

    @IBOutlet weak var txtEmail: UITextField!
    @IBOutlet weak var txtPassword: UITextField!
    @IBOutlet weak var signInActivity: UIActivityIndicatorView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func signInClick(sender: UIButton) {
        signInActivity.startAnimating()
        var restReq = RestRequest()
        restReq.delegate  = self
        var restParams = ["userEmail":"\(txtEmail.text)", "password":"\(txtPassword.text)"] as Dictionary<String, String>
        restReq.callRestAction(restParams, restAction: "AuthenticateUser")
    }

    func stopActivity()
    {
        println("Stopping the Activity Indiciator")

        // WHY DOES THIS LINE TAKE FOREVER TO STOP ANIMATING?
        self.signInActivity.stopAnimating()

        // IF I UNCOMMENT THIS NEXT LINE IT WILL STOP THE ANIMATION!
        //dispatch_async(dispatch_get_main_queue() , {self.signInActivity.stopAnimating()})
    }
    // MARK: - RestServiceDelegate

    func restServiceEndedWithError(message : String, calledRestAction : String) {
        stopActivity()
        println("Error with Rest Request: \(message) for Action: \(calledRestAction)")
    }

    func restServiceResponse(jsonResponse : NSDictionary, calledRestAction : String) {

        println("Response from Rest Request \(calledRestAction) with data \(jsonResponse)")

        if let userAuth : AnyObject = jsonResponse["AuthenticateUserResult"] {
            if userAuth as! Bool == true
            {
                println("User Authenticated: \(userAuth).")
            }
            else
            {
                println("Not Authenticated")
            }
        } else {
            println("Not Authenticated")
        }
        stopActivity()
    }
}

以下是调用Rest Action时的代码:

protocol RestServiceDelegate
{
    func restServiceResponse(jsonResponse : NSDictionary , calledRestAction : String)
    func restServiceEndedWithError(message : String, calledRestAction : String)
}

class RestRequest
{
    let appToken : String = "blah blah blah"
    let restURL : String = "http://blah blah blah"
    var delegate : RestServiceDelegate?

    func callRestAction(params : Dictionary<String,String>, restAction : String )
    {
        var url : String = restURL + restAction
        println("CALLING REST URL: \(url)")

        var request : NSMutableURLRequest = NSMutableURLRequest()
        request.URL = NSURL(string: url)
        request.HTTPMethod = "POST"

        var session = NSURLSession.sharedSession()
        var newParams = params
        newParams.updateValue(appToken, forKey: "appToken")

        var err: NSError?
        request.HTTPBody = NSJSONSerialization.dataWithJSONObject(newParams, options: nil, error: &err)
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")

        var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
            println("Response: \(response)")

            var strData : String = (NSString(data: data, encoding: NSUTF8StringEncoding) as? String)!

            println("Returned Result (BODY): \(strData)")

            var err: NSError?
            var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSDictionary

            if(err != nil)
            {
                self.delegate!.restServiceEndedWithError(err!.localizedDescription, calledRestAction: restAction)
            }
            else
            {
                self.delegate!.restServiceResponse(json!, calledRestAction: restAction)
            }
        })

        task.resume()
    }

}

0 个答案:

没有答案