LoginSignup
9
8

More than 5 years have passed since last update.

Swift Alamofire x Unbox x Wrap で通信処理を簡単にしてみましょう〜

Posted at

注意書き)秘伝のタレ(ノウハウ)や、実戦では必要なコードや綺麗なコードや私の好きなフォーマットなどはすべて除外してコード載せておきます。
エラーチェックや、ハンドリングや不具合など直す前のピュアなコードです。
使うときは自己責任でお願いいたします。

さて、Unbox/Wrap/Alamofire を組み合わせ私一人でウキウキしながら作った通信処理の一部分をご紹介します。
モデルクラスにラップしたりあんラップしたり、だるいですよね。。。
なんどもAlamofire.requestを書くのもだるいですよね・・・

そんなときはこんな感じにまとめてあげるといいですよ!
まぁ、向き不向きや、好き嫌いあるので、その辺は今回はスルーしてください!

    func requestt<T: Unboxable, U: WrapCustomizable>(
        method: Alamofire.Method,
        URLString: URLStringConvertible,
        structParameters: U?,
        headers: [String : String]?,
        completionBlock: ((unboxable: T?) -> Void)?,
        errorBlock: ((error: ErrorType?) -> Void)?) {

        var wrappedDictionary: WrappedDictionary? = nil
        if let parameters = structParameters {
            do {
                wrappedDictionary = try Wrap(parameters)
            } catch {
                errorBlock?(error: error)
                return
            }
        }

        Alamofire.request(method, URLString, parameters: wrappedDictionary, encoding: .JSON, headers: headers)
            .responseJSON(completionHandler: { (response: Response<AnyObject, NSError>) -> Void in
            debugPrint(response)
            let result: Result<AnyObject, NSError> = response.result

            if (result.isSuccess) {
                do {
                    let value: T = try UnboxOrThrow(result.value as! UnboxableDictionary)
                    completionBlock?(unboxable: value)
                } catch {
                    errorBlock?(error: error)
                }
            } else {
                errorBlock?(error: result.error)
            }
        })
    }

ご参考までに〜

9
8
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
9
8