The problem is loadVideos
, in which you made a very good asynchronous method and made it synchronous (block user interface updates) and made it rather inefficient with the while
. Instead, make loadVideos
asynchronous:
func loadVideos(url:String, completionHandler: (Array<JSON>?) -> ()) { var request = Get_Data() request.remoteUrl = url request.getData {data, error in println("los datos") //println(data) if (data != nil){ // Fix possible error if no "results" key if let results = data["results"].array { completionHandler(results) } println("Data reloaded") } else { println("api.getData failed") completionHandler(nil) } } }
And then userValid
should use the completion block parameter (using its own lock completion pattern):
func userValid(username :String, password : String, completionHandler: (Bool) -> ()) { userbase64 = encode_to_base64(username) passbase64 = encode_to_base64(password) var api = channelsFunction() api.loadVideos("https://api.cxntv.com/api/v1/videos/?type=canales&page_size=100&ordering=-id") { results in if results != nil { api.save_LiveChannels(results!) saver_user(userbase64, passbase64: passbase64, username: username, password: password) errormessage = "" completionHandler(true) }else{ completionHandler(false) } } }
And then login
will also call this asynchronously:
@IBAction func login(sender: AnyObject) { activity.hidden = false activity.startAnimating() if username.isEmpty || password.isEmpty { showAlert("Asegurese de ingresar un usuario y contraseña!") } else { userValid() { success in if !user.user_valid(self.username,password: self.password){ self.showAlert("Usuario Invalido") }else{ } dispatch_async(dispatch_get_main_queue(), { activity.hidden = true activity.stopAnimating() } } } }
I am sure that I do not have all of your functions and variables, but I hope you can see the pattern: Do not use synchronous methods and use completionHandler
parameters with your asynchronous methods.
-
If you want to see my original answer, which I posted before you shared the additional code, see the change history of this answer. But the main approach is outlined above.
source share