Last active
September 9, 2018 10:30
-
-
Save fumiyasac/05dc7572fd67a4cfa14e6b2f3e49c44a to your computer and use it in GitHub Desktop.
Alamofireの基本的な処理について
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
// その1: APIサーバーとの通信処理(JSONレスポンス取得) | |
/** | |
* APIへの通信処理: | |
* method: .get または .post | |
* parameters: [String : Any] 例. ["key" : value] | |
* encoding: JSONEncoding.default (パラメーターがない場合は不要) | |
* headers: [String : Any] 例. ["key" : value] (認可等が必要なユーザーのデータへアクセスしたい場合は必要) | |
*/ | |
Alamofire.request(url, method: .get or .post, parameters: params, encoding: JSONEncoding.default, headers: headers) | |
.responseJSON { response in | |
switch response.result { | |
// 処理成功時 | |
case .success: | |
// 以降はSwiftyJSON等を用いてResponseの解析 → Realmへの登録等を行う等 | |
// 処理失敗時 | |
case .failure(let error): | |
// エラーメッセージの表示等 | |
} | |
} | |
// その2: APIサーバーとの通信処理(画像ファイル等ダウンロード) | |
/** | |
* APIへの通信処理: | |
* method: .get または .post | |
* encoding: JSONEncoding.default | |
* to: ダウンロード時のファイルに関する設定 | |
*/ | |
// ダウンロード時のファイルに関する設定 | |
let destination: DownloadRequest.DownloadFileDestination = { _, response in | |
// 参考: https://stackoverflow.com/questions/39912905/download-file-using-alamofire-4-0-swift-3 | |
return (newpath, [.removePreviousFile, .createIntermediateDirectories]) | |
} | |
Alamofire.download(url, method: .get, encoding: JSONEncoding.default, to: destination) | |
.downloadProgress { progress in | |
// ダウンロード中に行う処理を記載 | |
} | |
.responseData { response in | |
// ダウンロード完了時に行う処理を記載 | |
switch response.result { | |
// 処理成功時 | |
case .success: | |
// タスクに成功したことを通知する | |
// 処理失敗時 | |
case .failure(let error): | |
// タスクに失敗したことを通知する | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment