Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
140 views
in Technique[技术] by (71.8m points)

json - Very strange issue in Swift code. Delay to make operations

I've a very strange issue I could't solve. I'm developing an iOS app using swift. In a class (class A), I call another class (class B) for connecting to a server. This server return a json, I pass the result to class A but I get an important delay for the operation I wish.

Here's the code of class A:

    func loginUser () {


    //check for data
    if txt_mail!.text == "" || txt_password!.text == ""{
        var alertView = UIAlertView(title: "Error", message: "no data", delegate: nil, cancelButtonTitle: "OK")
        alertView.show()
    }
    else
    {

        //save data and login
        var data:NSMutableDictionary = NSMutableDictionary(objects: [txt_mail!.text, txt_password!.text], forKeys: ["email", "password"])
        loginUserClass().loginUser(data)


    }

}

in class B i have:

 func loginUser (data:NSMutableDictionary) {


    var success_login:Int = 0
    userData = data

    //request for login
    var request = NSMutableURLRequest(URL: NSURL(string: "http://link_to_server")!)
    var session = NSURLSession.sharedSession()
    request.HTTPMethod = "POST"

    let email:String = userData.valueForKey("email") as! String
    let password:String = userData.valueForKey("password") as! String
    let auth:NSMutableDictionary = ["email":email,"token":password]


    var err: NSError?
    request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, 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

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

        if(err != nil) {
            //error
             success_login = 0
        }
        else {
             success_login = 1

            }

        }


        /*
        Now I call another func in class A for "working" the result
        */

        dispatch_async(dispatch_get_main_queue(), {

            loginWithMailScreen().LoginUser_result(success_login)

        })



    })

    task.resume()




}

so the func that works the result in class A is:

 func LoginUser_result (success:Int) {

    if success == 1{

        print("Success...")
        let alert = UIAlertView(title: "Good", message: "Success...", delegate: nil, cancelButtonTitle: "Ok")
        alert.show()


    }
    else if success == 0{

        print("Error...")
        let alert = UIAlertView(title: "Error", message: "I'm sorry", delegate: nil, cancelButtonTitle: "Ok")
        alert.show()
    }


}

It's strange because console prints "Success..." or "Error..." very quickly but app shows alert after about 10 seconds!!! Any idea about the reason and how I could solve???

PS: sorry for my bad english, I'm italian

EDIT: I think server is very fast, in fact like I said I've the right result (0 for wrong mail/password, 1 for right mail/password). the strange behavior, I guess, is the delay for alert

I edit my code like Sulthan suggested. There's another issue with code like that. In fact, I get no problem with alert (no delay) but no other function is possible (dismiss isn't working)!!!

Any idea?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are updating ui on from background thread. You have to update UI from main thread only.

dispatch_async(dispatch_get_main_queue(), {

  loginWithMailScreen().loginUser_result(success_login)

})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...