Github Search Repository with swift and APIKit
Introduction to APIKit
I am going to give a brief introduction of APIKit with swift, APIKit is a type-safe networking abstraction layer that associates request type with response type which simplifies the design and implementation of REST APIs.
Demo Codeprotocol RequestType: APIKit.Request {}
extension RequestType {
/// Base URL
var baseURL: URL {
return URL(string: "https://api.github.com")!
}
/// Header
var headerFields: [String : String] {
return [
"Accept": "application/json",
"Accept-Encoding": "gzip"
]
}
func intercept(urlRequest: URLRequest) throws -> URLRequest {
return urlRequest
}
func intercept(object: Any, urlResponse: HTTPURLResponse) throws -> Any {
guard (200..<300).contains(urlResponse.statusCode) else {
throw APIError(object: object)
}
return object
}
}
// MARK: - JSON Decode
extension RequestType where Response: Himotoki.Decodable {
func response(from object: Any, urlResponse: HTTPURLResponse) throws -> Self.Response {
return try decodeValue(object)
}
}
This APIClient Class will return to the Session Class for responding the data. struct APIClient {
public static var configuration = URLSessionConfiguration.default
static var session: Session {
self.configuration.urlCache?.diskCapacity = 0
self.configuration.urlCache?.memoryCapacity = 0
return Session(adapter: URLSessionAdapter(configuration: configuration))
}
struct Fetch {
static func get(query: String) -> Observable<APIClient.Fetch.ResponseFetchRepositoryDecode> {
return Session.sendRequest(
request: Fetch.GetFetchRepositoryRequest(query: query)
)
}
}
}
This is where we transform APIKit Session Class into Rx System so that we can use Observable for data response.extension Session {
func sendRequest<T: Request>(request: T) -> Observable<T.Response> {
return Observable.create{ [unowned self] observer in
let task = self.send(request) { result in
switch result {
case .success(let response):
observer.onNext(response)
case .failure(.responseError(let apiError as APIError)):
observer.onError(apiError)
case .failure(let error):
observer.onError(error)
}
}
return Disposables.create {
task?.cancel()
}
}
}
static func sendRequest<T: Request>(request: T) -> Observable<T.Response> {
return Session.shared.sendRequest(request: request)
}
}
Sample Github Search Repository using APIKit
Within this sample project, you can search any repositories in github, I am using APIKit in this project to request github API and response as webview. Maybe next sample I will use Moya lib instead of APIKit.
Intallation
In podfile, the add the following lines:# auto layoutp
pod 'SnapKit'
# Rx
pod 'ReactorKit'
pod 'RxCocoa'
pod 'RxSwift'
# APIKit
pod 'APIKit'
pod 'Himotoki'
pod 'Result'
# Swift Initializer
pod 'Then'
Sample Demo
Here is the Sample Code Github Here!!! Feel Free to check with this sample :D
Reference
이 문제에 관하여(Github Search Repository with swift and APIKit), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다
https://qiita.com/phansreypich/items/cdd5d8ebd5d1ea32b41f
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)
protocol RequestType: APIKit.Request {}
extension RequestType {
/// Base URL
var baseURL: URL {
return URL(string: "https://api.github.com")!
}
/// Header
var headerFields: [String : String] {
return [
"Accept": "application/json",
"Accept-Encoding": "gzip"
]
}
func intercept(urlRequest: URLRequest) throws -> URLRequest {
return urlRequest
}
func intercept(object: Any, urlResponse: HTTPURLResponse) throws -> Any {
guard (200..<300).contains(urlResponse.statusCode) else {
throw APIError(object: object)
}
return object
}
}
// MARK: - JSON Decode
extension RequestType where Response: Himotoki.Decodable {
func response(from object: Any, urlResponse: HTTPURLResponse) throws -> Self.Response {
return try decodeValue(object)
}
}
struct APIClient {
public static var configuration = URLSessionConfiguration.default
static var session: Session {
self.configuration.urlCache?.diskCapacity = 0
self.configuration.urlCache?.memoryCapacity = 0
return Session(adapter: URLSessionAdapter(configuration: configuration))
}
struct Fetch {
static func get(query: String) -> Observable<APIClient.Fetch.ResponseFetchRepositoryDecode> {
return Session.sendRequest(
request: Fetch.GetFetchRepositoryRequest(query: query)
)
}
}
}
extension Session {
func sendRequest<T: Request>(request: T) -> Observable<T.Response> {
return Observable.create{ [unowned self] observer in
let task = self.send(request) { result in
switch result {
case .success(let response):
observer.onNext(response)
case .failure(.responseError(let apiError as APIError)):
observer.onError(apiError)
case .failure(let error):
observer.onError(error)
}
}
return Disposables.create {
task?.cancel()
}
}
}
static func sendRequest<T: Request>(request: T) -> Observable<T.Response> {
return Session.shared.sendRequest(request: request)
}
}
Within this sample project, you can search any repositories in github, I am using APIKit in this project to request github API and response as webview. Maybe next sample I will use Moya lib instead of APIKit.
Intallation
In podfile, the add the following lines:
# auto layoutp
pod 'SnapKit'
# Rx
pod 'ReactorKit'
pod 'RxCocoa'
pod 'RxSwift'
# APIKit
pod 'APIKit'
pod 'Himotoki'
pod 'Result'
# Swift Initializer
pod 'Then'
Sample DemoHere is the Sample Code Github Here!!! Feel Free to check with this sample :D
Reference
이 문제에 관하여(Github Search Repository with swift and APIKit), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://qiita.com/phansreypich/items/cdd5d8ebd5d1ea32b41f텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)