ios - 如何以编程方式返回具有全局功能的 Root View Controller ?

标签 ios swift swift2

我有 3 个主要 VC(我的帐户、注册、登录)。然后我有一个 Swift 文件 (Manager.swift),我在其中设置了一个类函数,在注册或登录后它会关闭 VC。

管理器.swift

class Manager {

  class func registerUser(vc: UIViewController?, user_email : String, user_password : String){
    let myUrl = NSURL(string: hostURL + "userRegister.php")
    let request = NSMutableURLRequest(URL:myUrl!)

    request.HTTPMethod = "POST";
    // Compose a query string
    let postString = "user_email=\(user_email)&user_password=\(user_password)";

    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        data, response, error in

        if error != nil
        {
            print("error=\(error)")
            return
        }

        // You can print out response object
        print("response = \(response)")

        // Print out response body
        let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
        print("responseString = \(responseString)")

        //Let’s convert response sent from a server side script to a NSDictionary object:

        let myJSON = try!NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as? NSDictionary

        if let parseJSON = myJSON {

            let status = parseJSON["status"] as? String
            let msg = parseJSON["message"] as? String
            print("Status: \(status)")

            if(status != "Success")
            {
            UIAlert.displayAlert(vc, title: "Error", message: msg!, dismissTxt: "OK")
            }
            else{
                defaults.setBool(true, forKey: "isLoggedIn")

//My Failed attempt to go back to Root :C                    
vc?.navigationController?.popToRootViewControllerAnimated(true)
            }
        }

    }

    task.resume()

}


}

注册VC

buttonPressed(sender: AnyObject) {

  Manger.registerUser(self, user_email:username, user_password:password1234)

}

我使用 navigationController?.popToRootViewControllerAnimated 试图返回 它会工作,但有时应用程序会崩溃,吐出这个:

2015-10-02 14:51:01.410 Retail_Template[4551:261846] * Assertion failure in -[UIKeyboardTaskQueue waitUntilAllTasksAreFinished], /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit_Sim/UIKit-3505.16/Keyboard/UIKeyboardTaskQueue.m:378 2015-10-02 14:51:01.415 Retail_Template[4551:261846] * Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[UIKeyboardTaskQueue waitUntilAllTasksAreFinished] may only be called from the main thread.' *** First throw call stack: ( 0 CoreFoundation 0x009f8a94 __exceptionPreprocess + 180 1 libobjc.A.dylib 0x02b26e02 objc_exception_throw + 50 2 CoreFoundation 0x009f892a +[NSException raise:format:arguments:] + 138 3 Foundation 0x010bd3e6 -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 118 4 UIKit 0x021f9d2e -[UIKeyboardTaskQueue waitUntilAllTasksAreFinished] + 180 5 UIKit 0x019e14f2 -[UIKeyboardImpl setDelegate:force:] + 703 6 UIKit 0x019e122e -[UIKeyboardImpl setDelegate:] + 60 7 UIKit 0x01ddd1d6 -[UIPeripheralHost(UIKitInternal) _reloadInputViewsForResponder:] + 1208 8 UIKit 0x01de6bef -[UIPeripheralHost(UIKitInternal) _preserveInputViewsWithId:animated:reset:] + 502 9 UIKit 0x01de6c85 -[UIPeripheralHost(UIKitInternal) _preserveInputViewsWithId:animated:] + 57 10 UIKit 0x0190dd0a -[UINavigationController navigationTransitionView:didStartTransition:] + 1029 11 UIKit 0x01903bf4 -[UINavigationController _startCustomTransition:] + 5104 12 UIKit 0x01913c0b -[UINavigationController _startDeferredTransitionIfNeeded:] + 801 13 UIKit 0x01914d05 -[UINavigationController __viewWillLayoutSubviews] + 68 14 UIKit 0x01aded9f -[UILayoutContainerView layoutSubviews] + 252 15 UIKit 0x017cb16b -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 813 16 libobjc.A.dylib 0x02b3b059 -[NSObject performSelector:withObject:] + 70 17 QuartzCore 0x003ed60c -[CALayer layoutSublayers] + 144 18 QuartzCore 0x003e128e _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 388 19 QuartzCore 0x003e10f2 _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 26 20 QuartzCore 0x003d3c2b _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 317 21 QuartzCore 0x00407c23 _ZN2CA11Transaction6commitEv + 589 22 QuartzCore 0x00407fbd _ZN2CA11Transaction14release_threadEPv + 289 23 libsystem_pthread.dylib 0x04bc32f7 _pthread_tsd_cleanup + 93 24 libsystem_pthread.dylib 0x04bc3051 _pthread_exit + 108 25 libsystem_pthread.dylib 0x04bc3734 pthread_get_stackaddr_np + 0 26 libsystem_pthread.dylib 0x04bc0e0e start_wqthread + 30 ) libc++abi.dylib: terminating with uncaught exception of type NSException

不确定我在这里做错了什么。 任何解决方案将不胜感激。谢谢!

最佳答案

正如你的错误所说:

may only be called from the main thread.

您的操作应该被调用到主线程中。如下代码所示:

dispatch_async(dispatch_get_main_queue()) {
    //Perform your task here.
}

关于ios - 如何以编程方式返回具有全局功能的 Root View Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32902126/

相关文章:

ios - 无法在 iOS 实际设备 MobileFirst 项目上登录应用程序

swift - 如何知道类中正在运行哪个 UI 测试?当第二次测试开始时

ios - AWS dynamodb 查询大多数时候崩溃

ios - 快速在 UIViewController 中绘制一个部分圆圈

swift2 - 显示/隐藏状态栏导致 View 跳转

ios - 自动滚动时单元格文本复制到另一行(通过拖放)

ios - Swift 2.0 无法使用类型为 ([AnyObject],(_) -> _) 的参数列表调用 'map'

iOS:如何从 Firebase 检索创建时间/更新时间戳?

iOS 委托(delegate)和单例模式

ios - 使用playbackStoreID播放Apple Music歌曲时出现问题