在将用户“用户名”保存到内部数据库后,我使用下面的函数将当前根视图控制器替换为新的根视图控制器。虽然代码工作,我可以做一个转换,但它需要很长的时间来转换。可能会有15小时。
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
}
}我就是这样调用这个函数的:
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()
})
}我犯了什么错误吗。
更新:
我正在张贴我的职位职能。可能要花很长时间:
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()
}发布于 2015-05-18 08:28:43
我认为时间上最昂贵的是这条线:
self.managedObjectContext?.save(&error)因此,sou应该保存在背景中,或者在切换到viedDidAppear后在secondViewController上保存。
有了MagicalRecord,有了有用的方法saveWithBlock: completion:
更新:
若要动画视图,可以使用此方法:
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
})
}发布于 2015-05-19 04:08:15
我间接地解决了这个问题。在跟踪代码之后,我意识到以下组件导致了延迟:
其中3例和4例最高。
因此,为了解决这个问题,我在网上做了一些研究,认为最好的做法是加载EveryTimeRun视图控制器,然后在用户尚未登录的情况下,在此基础上加载FirstTimeRun。然后在成功登录后关闭FirstTimeRun。
我想这是实现我想做的事情的一个更好的方法。加载和卸载视图控制器缝得有点像一个黑客。
https://stackoverflow.com/questions/30298276
复制相似问题