Created
February 19, 2019 08:12
-
-
Save yoheiMune/9348a20e69ed8b85e281f26cae4cf4a0 to your computer and use it in GitHub Desktop.
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
class Api { | |
// 省略... | |
// コメントを追加. | |
static func addComment(postId: Int, comment: String, callback: @escaping ((String?) -> Void)) { | |
// APIトークンを取得. | |
guard let apiToken = UserDefaults.standard.string(forKey: "apiToken") else { | |
callback("ログインが必要です") | |
return | |
} | |
// URL作成. | |
let url = apiRoot + "/api/posts/\(postId)/comments?api_token=" + apiToken | |
let params: [String: Any] = [ | |
"comment" : comment | |
] | |
// リクエスト作成. | |
let request = Alamofire.request(url, method: .post, parameters: params, encoding: JSONEncoding.default) | |
// API実行 | |
request.responseJSON { dataResponse in | |
// ネットワーク圏外など. | |
if dataResponse.result.isFailure { | |
print(dataResponse.error ?? "") | |
callback("エラーが発生しました。") | |
return | |
} | |
// ステータスコードが 201 でない場合、エラー. | |
if dataResponse.response?.statusCode != 201 { | |
print(dataResponse.result.value ?? "") | |
callback("サーバーでエラーが発生しました") | |
return | |
} | |
// 成功. | |
callback(nil) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment