2015-06-20 64 views
2

我对Swift非常陌生。我试图建立一个应用程序 -成功登录后无法打开新窗口Post - Swift

我有一个登录屏幕,一旦用户键入正确的用户名和密码,用户将被重定向到一个新窗口。我已成功设法执行HTTP发布请求,但在此之后,我无法在成功登录时打开新窗口。

@IBAction func signinTapped(sender: UIButton) { 
    let parameters = "{\"email\": \""+txtUserName.text+"\", \"password\": \""+txtPassword.text+"\"}" ;//as Dictionary<String, String> 

    //create the url with NSURL  
    let url = NSURL(string: "https://myurl") //change the url 

    //create the session object  
    var session = NSURLSession.sharedSession() 

    let request = NSMutableURLRequest(URL: url!)  
    request.HTTPMethod = "POST" //set http method as POST 

    var err: NSError? 
    request.HTTPBody = parameters.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true);//NSJSONSerialization.dataWithJSONObject(parameters, options: nil, error: &err) // pass dictionary to nsdata object and set it as request body   
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")  
    request.addValue("application/json", forHTTPHeaderField: "Accept") 

    //create dataTask using the session object to send data to the server  
    var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in  
     println("Response: \(response)")   
     let strData = NSString(data: data, encoding: NSUTF8StringEncoding)   
     println(strData)   
     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)    
      println("Error could not parse JSON: '\(jsonStr)'")     
     }     
     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 

       var success = parseJSON["success"] as? Int  
       println("Succes: \(success)")     
      } 

      else {     
       // Woa, okay the json object was nil, something went worng. Maybe the server isn't running?    
       let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)      
       println("Error could not parse JSON: \(jsonStr)")     
      } 

     } 

    }) 

有人可以给我举个例子。任何帮助非常感谢。

非常感谢

这是崩溃日志由@Dharmesh Kheni

2015-06-20 16:53:44.028 Login[29072:191664] *** Assertion failure in -[UIKeyboardTaskQueue waitUntilAllTasksAreFinished], /SourceCache/UIKit_Sim/UIKit-3347.44/Keyboard/UIKeyboardTaskQueue.m:374 
2015-06-20 16:53:44.033 Login[29072:191664] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[UIKeyboardTaskQueue waitUntilAllTasksAreFinished] may only be called from the main thread.' 
*** First throw call stack: 
(
    0 CoreFoundation      0x000000010c932c65 __exceptionPreprocess + 165 
    1 libobjc.A.dylib      0x000000010e49dbb7 objc_exception_throw + 45 
    2 CoreFoundation      0x000000010c932aca +[NSException raise:format:arguments:] + 106 
    3 Foundation       0x000000010cdcf98f -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 195 
    4 UIKit        0x000000010d929936 -[UIKeyboardTaskQueue waitUntilAllTasksAreFinished] + 151 
    5 UIKit        0x000000010d3ca952 -[UIKeyboardImpl setDelegate:force:] + 473 
    6 UIKit        0x000000010d67560d -[UIPeripheralHost(UIKitInternal) _reloadInputViewsForResponder:] + 1002 
    7 UIKit        0x000000010d67d994 -[UIPeripheralHost(UIKitInternal) _preserveInputViewsWithId:animated:reset:] + 504 
    8 UIKit        0x000000010d30d531 -[UIViewController _presentViewController:modalSourceViewController:presentationController:animationController:interactionController:completion:] + 623 
    9 UIKit        0x000000010d30e7ae -[UIViewController _presentViewController:withAnimationController:completion:] + 3079 
    10 UIKit        0x000000010d310701 __62-[UIViewController presentViewController:animated:completion:]_block_invoke + 132 
    11 UIKit        0x000000010d310625 -[UIViewController presentViewController:animated:completion:] + 229 
    12 Login        0x000000010c70d420 _TFFC5Login7LoginVC12signinTappedFS0_FCSo8UIButtonT_U_FTGSQCSo6NSData_GSQCSo13NSURLResponse_GSQCSo7NSError__T_ + 3344 
    13 Login        0x000000010c70d723 _TTRXFo_oGSQCSo6NSData_oGSQCSo13NSURLResponse_oGSQCSo7NSError__dT__XFo_iTGSQS__GSQS0__GSQS1____iT__ + 51 
    14 Login        0x000000010c70abe1 _TPA__TTRXFo_oGSQCSo6NSData_oGSQCSo13NSURLResponse_oGSQCSo7NSError__dT__XFo_iTGSQS__GSQS0__GSQS1____iT__ + 81 
    15 Login        0x000000010c70d753 _TTRXFo_iTGSQCSo6NSData_GSQCSo13NSURLResponse_GSQCSo7NSError___iT__XFo_oGSQS__oGSQS0__oGSQS1___dT__ + 35 
    16 Login        0x000000010c70d7ba _TTRXFo_oGSQCSo6NSData_oGSQCSo13NSURLResponse_oGSQCSo7NSError__dT__XFdCb_dGSQS__dGSQS0__dGSQS1___dT__ + 90 
    17 CFNetwork       0x000000010f6a600b __49-[__NSCFLocalSessionTask _task_onqueue_didFinish]_block_invoke + 157 
    18 Foundation       0x000000010cdf357f __NSBLOCKOPERATION_IS_CALLING_OUT_TO_A_BLOCK__ + 7 
    19 Foundation       0x000000010cd340b2 -[NSBlockOperation main] + 98 
    20 Foundation       0x000000010cd16774 -[__NSOperationInternal _start:] + 645 
    21 Foundation       0x000000010cd16383 __NSOQSchedule_f + 184 
    22 libdispatch.dylib     0x000000010ebc1614 _dispatch_client_callout + 8 
    23 libdispatch.dylib     0x000000010eba86a7 _dispatch_queue_drain + 2176 
    24 libdispatch.dylib     0x000000010eba7cc0 _dispatch_queue_invoke + 235 
    25 libdispatch.dylib     0x000000010ebab3b9 _dispatch_root_queue_drain + 1359 
    26 libdispatch.dylib     0x000000010ebacb17 _dispatch_worker_thread3 + 111 
    27 libsystem_pthread.dylib    0x000000010ef2e6cb _pthread_wqthread + 729 
    28 libsystem_pthread.dylib    0x000000010ef2c4a1 start_wqthread + 13 
) 
libc++abi.dylib: terminating with uncaught exception of type NSException 

回答

4

可以启动新的视图控制器,这样,当用户成功登录:

if let parseJSON = json { 
     // Okay, the parsedJSON is here, let's get the value for 'success' out of it 

     var success = parseJSON["success"] as? Int 
     println("Succes: \(success)") 

     dispatch_async(dispatch_get_main_queue()) { 
      let storyboard = UIStoryboard(name: "Main", bundle: nil) 
      let vc = storyboard.instantiateViewControllerWithIdentifier("YourViewControllerID") as! UIViewController 
      self.presentViewController(vc, animated: true, completion: nil) 
     } 
    } 

而且不要忘记点击您的视图控制器上的故事板转到身份检查给予的标识符下一个视图设置故事板ID如下图所示图片:

enter image description here

希望它会帮助你。

+0

感谢@Dharmesh为您详细的提示reply.I确实正如你所说,但应用程序崩溃。 ***声明失败 - [UIKeyboardTaskQueue waitUntilAllTask​​sAreFinished],/SourceCache/UIKit_Sim/UIKit-3347.44/Keyboard/UIKeyboardTaskQueue.m:374 2015-06-20 16:28:25.797登录[27119:180067] ***终止应用程序由于未捕获异常'NSInternalInconsistencyException',原因:' - [UIKeyboardTaskQueue waitUntilAllTask​​sAreFinished]只能从主线程调用'。 – bably

+0

告诉我你的崩溃日志。 –

+0

@Dharnesh,我已经将崩溃报告添加到原始问题本身。所有你的帮助非常感谢。谢谢 – bably

0

成功登录的要求,

let vc = ViewController() //Your view controller to present 
self.presentViewController(vc, animated: true, completion: nil) 
0

试试这个

if(success == 1) 
{ 
let viewcontroller = self.storyboard?.instantiateViewControllerWithIdentifier("Storyboard Id") as viewcontrollerName 
var navController:UINavigationController = UINavigationController(rootViewController: viewcontroller) 
UIApplication.sharedApplication().keyWindow?.rootViewController = navController 
}