2014-10-01 1 views
7

신속하게이 블록 기능을 작성하는 방법은 무엇입니까? 주제에 대해 읽었지만 구문이 나에게별로 의미가 없습니다.Swift에서 블록 기능 작성

MyAppRequest *request = [_agent login]; 
    [request sendWithLoadMessage:@"Signing In" 
    successMessage:@"Signed In" 
    failureMessage:@"Failed to log in" 
    recoveryOptions:@"If you keep having trouble, try going to http://mystrou.firehosehelp.com and try loggin in there. If that fails, try resetting your password" 
    success:^(MyAppResponse *response) { 
     PREFS.authToken = _agent.accessToken; 
     [_delegate loginViewController:self loggedInAgent:_agent]; 
    } failure:^(MyAppResponse *response) { 

    }]; 
+1

더 많은 코드를 게시주십시오 - 실종 통화 부분이 있습니다. – fluidsonic

+0

그에 맞게 업데이트했습니다. – YichenBman

답변

19

사실 그리 어렵지 않습니다. Swift에서 폐쇄라고 불렀습니다).

public func someFunction(success: (response: AnyObject!) -> Void, failure: (error: NSError?) -> Void) { 

} 

여기에 전화하는 방법이 있습니다. 귀하의 경우에는

someFunction(success: { (response) -> Void in 
    // Handle success response 
}) { (error?) -> Void in 
    // Do error handling stuff 
} 

, 나는이 블록을 받고 있어요 일부 서버의 응답을 처리합니다. 대개 로그인했을 것입니다. 네트워크 작업이 성공하면 success 블록이 호출됩니다. 그 안에는받은 액세스 토큰을 서버에서 저장합니다.

네트워크 요청이 실패하면 failure 블록이 호출됩니다. 오류를 로그 아웃하고 사용자에게 경고 메시지를 표시 할 수 있습니다.

구문에 대해 혼란 스러우면이 두 사이트를 참조하십시오. Objective-C block syntaxSwift closure syntax에 대해. 나는이 알아 낸 @isuru에

0

감사 :

let request: MyAppRequest = agent .login() 

request .sendWithLoadMessage("Signing in", 
     successMessage: "Signed in", 
     failureMessage: "Failed to login", 
     recoveryOptions: "Figuring it out", 
     success: { (response: MyAppResponse!) -> Void in MyAppSettings().authenticatingToken = agent.accessToken 
     }) { (response: MyAppResponse!) -> Void in 
      var alert = UIAlertController(title: "Oops!", message: "You haven't figured out the token thing!", preferredStyle: UIAlertControllerStyle.Alert) 

      alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.Default, handler: nil)) 
      self.presentViewController(alert, animated: true, completion: nil) 
    }