首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >iOS应用程序:使用swift进行登录后交换Swapping控制器有明显的延迟

iOS应用程序:使用swift进行登录后交换Swapping控制器有明显的延迟
EN

Stack Overflow用户
提问于 2015-05-18 08:21:34
回答 2查看 888关注 0票数 1

在将用户“用户名”保存到内部数据库后,我使用下面的函数将当前根视图控制器替换为新的根视图控制器。虽然代码工作,我可以做一个转换,但它需要很长的时间来转换。可能会有15小时。

代码语言:javascript
复制
    func switchRootViewController(rootViewController: UIViewController, animated: Bool, completion: (() -> Void)?) {
    if animated {
        UIView.transitionWithView(self.window!, duration: 0.5, options: .TransitionCrossDissolve, animations: {
            let oldState: Bool = UIView.areAnimationsEnabled()
            UIView.setAnimationsEnabled(false)
            self.window!.rootViewController = rootViewController
            UIView.setAnimationsEnabled(oldState)
            }, completion: { (finished: Bool) -> () in
                if (completion != nil) {
                    completion!()
                }
        })
    } else {
        self.window!.rootViewController = rootViewController
    }
}

我就是这样调用这个函数的:

代码语言:javascript
复制
   api.postMulti(apiKey, contentType: "application/json", payLoad: payLoad, urlString: urlString, parameter: parameter){ (succeeded: Int, msg: String) -> () in

        var alert = UIAlertView(title: "Failed", message: msg, delegate: nil, cancelButtonTitle: "Okay")

        if succeeded == 422 {
            alert.title = "Failed"
            alert.message = "Username is already in use. Please selecet another one!"
        }

        else if succeeded == 500{
            alert.title = "Failed"
            alert.message = "Internal Server Error. Unable to process Request!"
        }

        else if succeeded == 200{
            //save to internal DataBase table: User
            let entityDescription = NSEntityDescription.entityForName("User", inManagedObjectContext: self.managedObjectContext!)

            let users = User(entity: entityDescription!, insertIntoManagedObjectContext: self.managedObjectContext)

            users.username = self.userName.text

            var error: NSError?

            self.managedObjectContext?.save(&error)

            if let err = error {
                println(err.localizedFailureReason)
            } else {

                self.userName.text = ""
                alert.title = "Success"
                alert.message = "Loading App..."



                let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
                var secondViewController: EveryTimeRun = mainStoryboard.instantiateViewControllerWithIdentifier("everytime") as! EveryTimeRun

                self.switchRootViewController(secondViewController, animated: true, completion: nil)




                self.window?.makeKeyAndVisible()


            }
        }

        // Move to the UI thread
        dispatch_async(dispatch_get_main_queue(), { () -> Void in
            // Show the alert
            alert.show()
        })
    }

我犯了什么错误吗。

更新:

我正在张贴我的职位职能。可能要花很长时间:

代码语言:javascript
复制
        func postMulti(apikey: String, contentType: String, payLoad: Dictionary<String,Dictionary<String,String>>, urlString: String, parameter: String, postCompleted : (succeeded: Int, msg: String) -> ()){

    let joinedUrl = urlString + parameter
    let url = NSURL(string: joinedUrl)
    let request = NSMutableURLRequest(URL: url!)

    var session = NSURLSession.sharedSession()
    request.HTTPMethod = "POST"
    request.addValue(contentType, forHTTPHeaderField: "Content-Type")
    request.addValue(apikey, forHTTPHeaderField: "apikey")
    var error: NSError?


    let payLoadJSON = NSJSONSerialization.dataWithJSONObject(payLoad, options: nil, error: &error)
    request.HTTPBody = payLoadJSON

    var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
        var strData = NSString(data: data, encoding: NSUTF8StringEncoding)


        var err: NSError?
        var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSDictionary
        // Did the JSONObjectWithData constructor return an error? If so, log the error to the console
        if(err != nil) {
            //            println(err!.localizedDescription)
            let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)

            postCompleted(succeeded: 0, msg: "Portal is not reachable. Please try again later")
        }
        else {
            // The JSONObjectWithData constructor didn't return an error. But, we should still
            // check and make sure that json has a value using optional binding.
            if let parseJSON = json {
                // Okay, the parsedJSON is here, let's get the value for 'success' out of it
                if let statusCode = parseJSON["statusCode"] as? Int {

                    postCompleted(succeeded: statusCode, msg: "")
                }
            }
            else {
                // Woa, okay the json object was nil, something went worng. Maybe the server isn't running?
                let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)

                postCompleted(succeeded: 1, msg: "Portal is not reachable. Please try again later")
            }
        }
    })

    task.resume()
}
EN

回答 2

Stack Overflow用户

发布于 2015-05-18 08:28:43

我认为时间上最昂贵的是这条线:

代码语言:javascript
复制
self.managedObjectContext?.save(&error)

因此,sou应该保存在背景中,或者在切换到viedDidAppear后在secondViewController上保存。

有了MagicalRecord,有了有用的方法saveWithBlock: completion:

更新:

若要动画视图,可以使用此方法:

代码语言:javascript
复制
var overlaywindow: UIWindow!
//

var storyboard = UIStoryboard(name: "Main", bundle: nil)

    if let popupVC = storyboard.instantiateViewControllerWithIdentifier("everytime") as? EveryTimeRun
    {
        var frame = UIScreen.mainScreen().bounds
        overlayWindow = UIWindow(frame: frame)

        popupVC.overlayWindow = overlayWindow
        overlayWindow.windowLevel = UIWindowLevelAlert
        overlayWindow.rootViewController = popupVC

        overlayWindow.makeKeyAndVisible()
        overlayWindow.alpha = 0

        UIView.animateWithDuration(0.3, animations:
        {
            self.overlayWindow.alpha = 1
        })
    }
票数 0
EN

Stack Overflow用户

发布于 2015-05-19 04:08:15

我间接地解决了这个问题。在跟踪代码之后,我意识到以下组件导致了延迟:

  1. 调用rest网络延迟的POST方法
  2. 将用户名保存到CoreData -写延迟
  3. 卸载现有(ID: FirstTimeRun)视图控制器-卸载延迟
  4. 加载一个新的选项卡(ID: EveryTimeRun)视图控制器-加载延迟

其中3例和4例最高。

因此,为了解决这个问题,我在网上做了一些研究,认为最好的做法是加载EveryTimeRun视图控制器,然后在用户尚未登录的情况下,在此基础上加载FirstTimeRun。然后在成功登录后关闭FirstTimeRun。

我想这是实现我想做的事情的一个更好的方法。加载和卸载视图控制器缝得有点像一个黑客。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30298276

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档