Lento con forza

大学生気分のIT系エンジニアが色々書いてく何か。ブログ名決めました。

Swiftで簡易APIクライアント

AFNetworkingを使った簡易クライアントをSwiftで書いてみました。

Objective-CのライブラリをSwiftで利用

Cocoa Podsかなんかで適当にAFNetworkingを入れておきます。

SwiftでCocoaPodsを使う - Qiita

APIClientを作成

AFHTTPSessionManagerのサブクラスを作る形でAPIクライアントを作成します。
AFHTTPSessionManagerはiOS6以下では利用することができないので、iOS6以下をターゲットにしている方は以下の方法は使えません。

MyClient.swift

import UIKit

class MyClientRequestSerializer: AFHTTPRequestSerializer{
    override func requestWithMethod(method: String!, URLString: String!, parameters: AnyObject!, error:NSErrorPointer) -> NSMutableURLRequest! {        
        var path:NSString = URLString + "?"
       
        var dictParameters:Dictionary<String, String>
        if (parameters != nil){
            dictParameters = parameters as Dictionary<String, String>
        }
        else{
            dictParameters = Dictionary<String, String>()
        }
        
        for key in dictParameters.keys{
            let value = dictParameters[key]
            
            path = path.stringByAppendingFormat("&%@=%@", key, value!)
        }
        
        let req = super.requestWithMethod(method, URLString: path, parameters: nil, error: error)
        
        return req
    }
   
}

class MyClient: AFHTTPSessionManager {
   
    class var sharedInstance : MyClient {
        struct Static {
            static var instance : MyClient = MyClient(baseURL:NSURL(string:"https://api.github.com/"))
        }
        return Static.instance
    }
    
    override init(baseURL url: NSURL!, sessionConfiguration configuration: NSURLSessionConfiguration!) {
        super.init(baseURL: url, sessionConfiguration: nil)
    }
    
    override init(baseURL url: NSURL!) {
        super.init(baseURL: url)
        let requestSerializer = MyClientRequestSerializer()
        self.requestSerializer = requestSerializer
        // If you need a responseSerializer, you can write it
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func yourAPI(){
        self.GET("users/kouki-dan/repos",
            parameters: ["none":"none"],
            success: { (task, response) in
                println(response)
            },
            failure: { (error) in
                println("error")
        })

    }
    func yourAPI2(id:NSString){
        //...
    }
    //.......
}

APIクライアントはこのような感じになります。
yourAPIの所でエンドポイントを記述して、実際にHTTPリクエストを呼び出しています。

APIを利用する時は

func yourFunc(){
    let sharedClient = MyClient.sharedInstance
    sharedClient.yourAPI()
}

のように使います。

簡単な例をgithubにあげときました。

kouki-dan/SimpleAPIClient · GitHub