ios - 为什么我的登录功能出现此错误

标签 ios xcode swift completionhandler

我有一个登录功能,当用户有效时我没有问题,但是当用户isvalid时我有这个错误

" Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[UIKeyboardTaskQueue waitUntilAllTasksAreFinished] may only be called from the main thread."

这是我的代码。

@IBAction func login(sender: AnyObject) {
    var valid: Bool = false
    //activity.startAnimating()
    self.viewUtils.showActivityIndicator(self.view)
    username =  userField.text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
    password = passwordTextField.text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())

        if (self.username.isEmpty || self.password.isEmpty){
            self.showAlert("Inserte usuario password")
        }

        else{                   
            var user = UserFunction()
            user.userValid(self.username,password: self.password){ success in

                if success == true{
                    //self.activity.stopAnimating()
                    self.performSegueWithIdentifier("showTable", sender: self )
                }else{
                    println("me quedo aqui")
                    //self.activity.stopAnimating()
                    self.showAlert("usuario incorrecto")//ver porque no entra a usuario incorrecto

                }
           }
    }
}

func userValid(username :String, password : String, completionHandler:(Bool)->()){
    var valid: Bool!
    var resultados : Array<JSON> = []
    userBase64 = self.encodeToBase64(username)
    passBase64 = self.encodeToBase64(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){
            errorMessage = ""
            println("devuelvo true")
            api.saveLiveChannels(results!)
            self.saveUser(userBase64, passbase64: passBase64, username: username, password: password)
            completionHandler(true)
        }else{
            println("devuelvo false")
            completionHandler(false)
    }
    }
}

最佳答案

如果您正在与某个 API 进行交互,而该 API 恰好生成了一个线程并在后台运行您的代码,那么您将在主线程上运行。

以这种方式在主线程中呈现您的警报:

dispatch_async(dispatch_get_main_queue()) {
    self.showAlert("usuario incorrecto")
}

或者,如果您要更新任何其他 UI,则必须在主线程中执行此操作,如上面的代码所示。

有关更多信息,请阅读这篇文章:GCD to perform task in main thread

关于ios - 为什么我的登录功能出现此错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31914526/

相关文章:

iphone - 使用 AVFoundation 播放视频时遇到问题

ios - UIScrollView 内的 UIButton 禁用滚动

ios - 用 NSFetchRequest => [数组计数] 错误填充 NSArray

ios - PromiseKit 是否有 RxSwift Zip 替代品?

swift - 如何发送包含字符串的消息结构作为 Game Center 的 NSData

iOS Animate 高度限制问题

ios - 我的 EXC_BAD_ACCESS (Code = 2) 错误的原因是什么?

iphone - Facebook iOS SDK戳

iphone - 垂直折叠动画

ios - 拍摄照片或从照片库中选择照片后,UIImageView 未使用新图像更新