Combine Frameworkcan be used to build robust and reusable Network Services in an iOS app. In this post I will demonstrate how to create a Network Service with Combine and Alamofire.
First let’s add Alamofire to the Podfile.
platform :ios, '11.0'
target 'Project' do
# Comment the next line if you don't want to use dynamic frameworks
use_frameworks!
# Pods for Project
pod 'Alamofire', '~> 5.2'
end
Now Let’s check the **CoreService **struct.
import Combine
import Alamofire
struct CoreService {
static func request<T: Decodable, E: Error>(
url: String,
method: HTTPMethod,
parameters: Parameters?,
decoder: JSONDecoder = JSONDecoder(),
headers: HTTPHeaders? = nil
) -> Future<T, E> {
return Future({ promise in
AF.request(
url,
method: method,
parameters: parameters,
headers: headers
).responseDecodable(decoder: decoder, completionHandler: { (response: DataResponse<T, AFError>) in
switch response.result {
case .success(let value):
promise(.success(value))
case .failure(let error):
promise(.failure(
NSError(domain: error.destinationURL?.absoluteString ?? "", code: error.responseCode ?? 0) as! E
)
)
}
})
})
}
}
The **request **method defines type **T **which conforms to **Codable **(Encodable or Decodable protocols) and type E which conforms to **Error **protocol as type parameters. It returns a Futurewhich takes in type **T **as Output and type **E **as Failure.
Here is the **ExampleService **struct.
import Combine
import Alamofire
struct ExampleService {
static func getData(_ parameters: [String: String]) -> Future<EditionResponse, Error> {
let url = Constants.baseUrl + Constants.versionUrl + Constants.editionUrl
return CoreService.request(
url: url,
method: HTTPMethod.get,
parameters: parameters
)
}
}
ExampleService defines a getData method that has parametersdictionary as its parameter and returns a Future<EditionResponse, Error>. It calls **CoreService.request **passing **HTTPMethod.get **which makes this request an **HTTP GET **request.
#ios #swift #programming