Swift51.com
Swift 头像
Swift  2016-01-24 17:18

Web API客户端 APIKit

回复:0  查看:4871  感兴趣:14  赞:0  

APIKit是构建类型安全的Web API客户端,用Swift编写。

示例代码:

protocol GitHubRequestType: RequestType {

}

extension GitHubRequestType {
    var baseURL: NSURL {
        return NSURL(string: "https://api.github.com")!
    }
}

struct GetRateLimitRequest: GitHubRequestType {
    typealias Response = RateLimit

    var method: HTTPMethod {
        return .GET
    }

    var path: String {
        return "/rate_limit"
    }

    func responseFromObject(object: AnyObject, URLResponse: NSHTTPURLResponse) -> Response? {
        guard let dictionary = object as? [String: AnyObject] else {
            return nil
        }

        guard let rateLimit = RateLimit(dictionary: dictionary) else {
            return nil
        }

        return rateLimit
    }
}

struct RateLimit {
    let count: Int
    let resetDate: NSDate

    init?(dictionary: [String: AnyObject]) {
        guard let count = dictionary["rate"]?["limit"] as? Int else {
            return nil
        }

        guard let resetDateString = dictionary["rate"]?["reset"] as? NSTimeInterval else {
            return nil
        }

        self.count = count
        self.resetDate = NSDate(timeIntervalSince1970: resetDateString)
    }
}

相关开源代码