Forest Client는 URLSession 및 URLSessionTask 위에 구축 된 유연하고 확장 가능한 RESTFUL API 클라이언트 프레임 워크입니다. 이미 JSON에서 가장 일반적으로 사용되는 데이터 유형까지 네트워크 객체 맵퍼가 포함되어 있습니다. 간단한 데이터 인코딩/디코딩 접근 방식과 확장 가능한 아키텍처로 인해 사용자 정의 네트워크 객체 매퍼를 쉽게 추가 할 수 있습니다. Forest는 백엔드 서비스를 위해 강력한 클라이언트를 구축하는 데 필요한 모든 기능을 제공합니다.
다른 입증 된 네트워킹 프레임 워크를 얻지 않는 이유를 물어볼 수 있습니까? 물론, 당신은 당신의 요구와 스타일 선호도에 가장 적합한 하나를 얻을 수 있지만, 항상 옵션을 갖는 것이 좋습니다. 다음은 고급 네트워킹 계층에서 원하는 기능 목록이며 Forest Client에서 구현됩니다.
Decodable 프로토콜을 준수하는 객체를 사용합니다. pod 'Forest'확장을지지하는 프로토 비프 추가 :
pod 'Forest/Protobuf'도달 가능성 서비스 사용 :
pod 'Forest/Reachability'프레임 워크를 가져 오는 것을 잊지 마십시오.
import Forest 프로젝트에 Core 및 Protobuf 디렉토리의 파일을 넣으십시오. Protobuf 확장을 사용하려면 SwiftProtobuf 프레임 워크를 프로젝트에 추가로 통합해야합니다.
네트워크 작업을 처리하는 핵심 클래스는 ServiceTask 입니다. ServiceTask 요청 및 응답 매개 변수 및 처리기를 구성하는 데 도움이되는 공장 방법이 포함되어 있습니다. 응답을 처리하고 처리하는 프로세스를 더 많이 제어 해야하는 경우 대표단을 사용하여 ServiceTaskRetrofitting 프로토콜을 구현하고 리트로 터를 통해 작업 동작을 수정할 수 있습니다. 또한 서브 클래스 ServiceTask 할 수 있습니다.이를 위해 제작되었습니다.
ServiceTask ( )
. url ( " https://host.com/path/to/endpoint " )
. method ( . GET )
. query ( [ " param " : value ] )
// Expecting valid JSON response
. json { ( object , response ) in
print ( " JSON response received: ( object ) " )
}
. error { ( error , response ) in
print ( " Error occurred: ( error ) " )
}
. perform ( )코드 가능한 프로토콜을 준수하는 개체를 사용하여 데이터를 보내고 수신합니다.
struct NameRequest : Encodable {
let name : String
}
struct NameResponse : Decodable {
let isValid : Bool
}
ServiceTask ( )
// Set base url and HTTP method
. endpoint ( . POST , " https://host.com " )
// Add path to resource
. path ( " /path/to/resource " )
// Serialize our Codable struct and set body
. body ( codable : NameRequest ( " some " ) )
// Expect response with the object of 'NameResponse' type
. codable { ( object : NameResponse , response ) in
print ( " Name valid: ( object . isValid ) " )
}
// Otherwise will fail with error
. error { ( error , response ) in
print ( " Error occured: ( error ) " )
}
. perform ( )일부 파일을 다운로드하기 만하면됩니다.
ServiceTask ( )
. headers ( [ " Authorization " : " Bearer ( token ) " ] )
. method ( . PUT )
. url ( " https://host.com/file/12345 " )
. body ( text : " 123456789 " )
. file { ( url , response ) in
print ( " Downloaded: ( url ) " )
// Remove temp file
try ? FileManager . default . removeItem ( at : url )
}
. error { ( error , response ) in
print ( " Error occured: ( error ) " )
}
// When download destination not provided, content will be downloaded and saved to temp file
. download ( )멀티 파트 양식 데이터 인코딩 된 컨텐츠 업로드 :
do {
// Create new form data builder
var formDataBuilder = FormDataBuilder ( )
// Filename and MIME type will be obtained automatically from URL. It can be provided explicitly too
formDataBuilder . append ( . file ( name : " image " , url : * url * ) )
// Generate form data in memory. It also can be written directly to disk or stream using encode(to:) method
let formData = try formDataBuilder . encode ( )
ServiceTask ( )
. endpoint ( . POST , " https://host.com/upload " )
. body ( data : formData , contentType : formDataBuilder . contentType )
. response ( content : { ( response ) in
switch response {
case . success :
print ( " Done! " )
case . failure ( let error ) :
print ( " Failed to upload: ( error ) " )
}
} )
. perform ( )
}
catch {
print ( " ( error ) )
return
}
Protobuf 메시지를 보내고 받으십시오 (HTTP를 통해 grpc) :
ServiceTask ( )
. endpoint ( . POST , " https://host.com " )
// Create and configure request message in place
. body { ( message : inout Google_Protobuf_StringValue ) in
message . value = " something "
}
// Expecting Google_Protobuf_Empty message response
. proto { ( message : Google_Protobuf_Empty , response ) in
print ( " Done! " )
}
. error { ( error , response ) in
print ( " Error occured: ( error ) " )
}
. perform ( )
// Or another version of the code above with explicitly provided types
ServiceTask ( )
. endpoint ( . POST , " https://host.com " )
// Create and configure request message in place
. body ( proto : Google_Protobuf_SourceContext . self ) { ( message ) in
message . fileName = " file.name "
}
// Expecting Google_Protobuf_Empty message response
. response ( proto : Google_Protobuf_Empty . self ) { ( response ) in
switch response {
case . success ( let message ) :
print ( " Done! " )
case . failure ( let error ) :
print ( " Error occured: ( error ) " )
}
}
. perform ( ) Natan Zalkin [email protected]
Forest는 MIT 라이센스에 따라 제공됩니다. 자세한 내용은 라이센스 파일을 참조하십시오.