Created
September 9, 2018 10:28
-
-
Save fumiyasac/2e56baf3d21b2885de7aeaa1819c3103 to your computer and use it in GitHub Desktop.
Boltの基本的な使い方
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Alamofireと組み合わせて利用する | |
*/ | |
// Modelファイル内のメソッド定義 | |
func getDataFromAPI() -> BFTask<AnyObject> { | |
let taskCompletion = BFTaskCompletionSource<AnyObject>() | |
let url = "..." | |
Alamofire.request(url, method: .get) | |
.responseJSON { response in | |
if let json = response.result.value { | |
// 値の取得が成功した場合 | |
taskCompletion.set(result: true as AnyObject) | |
} else { | |
// 値の取得が成功した場合 | |
taskCompletion.set(error: error) | |
} | |
} | |
return taskCompletion.task | |
} | |
/** | |
* case1. 単発で処理が終了する | |
*/ | |
// 画面ViewControllerからModelを利用する | |
let task = Model.getDataFromAPI() | |
// 後続処理が1つしかない場合 | |
task.continueWith(block: { (task: BFTask!) -> AnyObject? in | |
if task.error == nil { | |
// 成功時の処理 | |
} else { | |
// 失敗時の処理 | |
} | |
}) | |
/** | |
* case2. 複数回後続処理をする | |
*/ | |
// 画面ViewControllerからModelを利用する | |
let task = Model.getDataFromAPI() | |
// 後続処理が複数回続く場合 | |
task.continueWith(block: { (task: BFTask!) -> BFTask<AnyObject> in | |
// 処理1を実行 | |
}).continueWith(block: { (task: BFTask!) -> BFTask<AnyObject> in | |
// 処理2を実行 | |
}).continueWith(block: { (task: BFTask!) -> BFTask<AnyObject> in | |
// ... 無事に処理が全部終わった最後は下記のようにする ... | |
}).continueOnSuccessWith(block: { (task: BFTask!) -> AnyObject? in | |
// 以前の全ての処理が完了した場合に実行する処理 | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment