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 
}