30
38

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Alamofire4 + swift3 のサンプル

Last updated at Posted at 2016-10-12

この組み合わせの例がまだ少なかったので

環境

  • swift 3.0
  • Almofire 4.0.1
  • xcode 8.0

汎用的に利用するためのサンプル

ApiManager.swift

import Alamofire

private let host = "https://example.com"

struct ApiManager {
    let url: String
    let method: HTTPMethod
    let parameters: Parameters

    init(path: String, method: HTTPMethod = .get, parameters: Parameters = [:]) {
        url = host + path
        self.method = method
        self.parameters = parameters
    }

    func request(success: @escaping (_ data: Dictionary<String, Any>)-> Void, fail: @escaping (_ error: Error?)-> Void) {
        Alamofire.request(url, method: method, parameters: parameters).responseJSON { response in
            if response.result.isSuccess {
                success(response.result.value as! Dictionary)
            }else{
                fail(response.result.error)
            }
        }
    }
}

使う側

  let api = ApiManager(path: "/users.json")
  api.request(success: { (data: Dictionary) in debugPrint(data) }, fail: { (error: Error?) in print(error) })

swift初めて書くので指摘あれば編集リクエスト下さい。

30
38
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
30
38

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?