I just learn how to create a protocol oriented networking, but I just don't get how to add page for pagination in protocol. my setup is like this
protocol Endpoint {
var base: String { get }
var path: String { get }
}
extension Endpoint {
var apiKey: String {
return "api_key=SOME_API_KEY"
}
var urlComponents: URLComponents {
var components = URLComponents(string: base)!
components.path = path
components.query = apiKey
return components
}
var request: URLRequest {
let url = urlComponents.url!
return URLRequest(url: url)
}
}
enum MovieDBResource {
case popular
case topRated
case nowPlaying
case reviews(id: Int)
}
extension MovieDBResource: Endpoint {
var base: String {
return "https://api.themoviedb.org"
}
var path: String {
switch self {
case .popular: return "/3/movie/popular"
case .topRated: return "/3/movie/top_rated"
case .nowPlaying: return "/3/movie/now_playing"
case .reviews(let id): return "/3/movie/\(id)/videos"
}
}
}
and this is my network service class method
func getReview(movie resource: MovieDBResource, completion: #escaping (Result<MovieItem, MDBError>) -> Void) {
print(resource.request)
fetch(with: resource.request, decode: { (json) -> MovieItem? in
guard let movieResults = json as? MovieItem else { return nil }
return movieResults
}, completion: completion)
}
How I add page in protocol so I can called and add parameter in viewController, for now my service in my viewController is like this. I need parameter to page
service.getReview(movie: .reviews(id: movie.id)) { [weak self] results in
guard let self = self else { return }
switch results {
case .success(let movies):
print(movies)
case .failure(let error):
print(error)
}
}
Thank you
You can add it as a parameter to your enum case like:
case popular(queryParameters: [String: Any])
You can create Router class that has buildRequest(_:Endpoint), and here you can get the queryParameters and add it to the url witch will contain page and limit or any other query parameters.
you can also add another parameter for bodyParameters if the request HTTPMethod is POST and you need to send data in the body.
Related
I have been working to re-implement a healthy network layer in our app and Routers are noted in many tutorials / Alamofire documentation. The app has a lot of endpoints, to keep things readable I want to split them out into their subset of services. That was also noted as a best practice.
The very first endpoint that I implemented works perfectly fine, but, when I create another Router there is the asURLRequest() function which would pretty much be a duplicate. The only difference could be the switch/case. Otherwise its almost certain to be the same.
To do this in Kotlin or Java, I would create a class and extend the function calling the super. Im not certain how that works here in Swift.
enum AuthenticationRouter: URLRequestConvertible {
case login(username:String, password:String)
// MARK: - HTTPMethod
private var method: HTTPMethod {
switch self {
case .login:
return .get
}
}
// MARK: - Path
private var path: String {
switch self {
case .login:
return "users/login"
}
}
// MARK: - Parameters
private var parameters: Parameters? {
switch self {
case .login:
return nil
}
}
// MARK: - URLRequestConvertible
func asURLRequest() throws -> URLRequest {
let url = try K.TestServer.baseURL.asURL()
var urlRequest = URLRequest(url: url.appendingPathComponent(path))
// HTTP Method
urlRequest.httpMethod = method.rawValue
// Common Headers
urlRequest.setValue(ContentType.json.rawValue, forHTTPHeaderField: HTTPHeaderField.acceptType.rawValue)
urlRequest.setValue(ContentType.json.rawValue, forHTTPHeaderField: HTTPHeaderField.contentType.rawValue)
switch self {
case .login(let username, let password):
// Handle adjusting headers or request as needed
default: ()
}
// Parameters
if let parameters = parameters {
do {
urlRequest.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: [])
} catch {
throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error))
}
}
return urlRequest
}
}
Here is and old code I used. I’d change the base class to protocol instead and continue your usage of enums that conforms to that protocol I like it much better.
import Alamofire
protocol API {
var method: HTTPMethod { get }
var encoding: ParameterEncoding? { get }
var parameters: Parameters { get }
var headers: HTTPHeaders { get }
var timeout:TimeInterval { get }
var path: String { get }
var baseUrl: String { get }
}
class Router: API {
var method: HTTPMethod { .get }
var encoding: ParameterEncoding? { JSONEncoding.default }
var parameters: Parameters {
let params = Parameters()
return params
}
var headers: HTTPHeaders {
let headers = HTTPHeaders()
// TODO - add defualt headers if needed
return headers
}
var timeout: TimeInterval {
#if DEBUG
return 120
#else
return 30
#endif
}
var path: String {
fatalError("Must be overridden in subclass")
}
var baseUrl: String { Consts.serverUrl }
}
extension Router: URLRequestConvertible {
open func asURLRequest() throws -> URLRequest {
guard let baseURL = URL(string: baseUrl) else { throw someError }
let appendedURL = baseURL.appendingPathComponent(path)
let urlRequest = try URLRequest(url: appendedURL, method: method)
guard let encoder = encoding else { throw someError }
var eUrlRequest = try encoder.encode(urlRequest, with: parameters)
eUrlRequest.timeoutInterval = timeout
headers.forEach { eUrlRequest.addValue($0.value, forHTTPHeaderField: $0.name) }
return eUrlRequest
}
}
And then an example UserRouter would be
import Alamofire
final class UserRouter: Router {
enum Endpoint {
case signIn(userName: String, password: String)
}
let endpoint: Endpoint
init(endpoint: Endpoint) {
self.endpoint = endpoint
}
override var method: HTTPMethod {
.get
}
override var parameters: Parameters {
var params = super.parameters
switch endpoint {
case .signIn(let userName, let password):
params[“login”] = [“username”: userName, “password”: password]
}
return params
}
override var path: String {
switch endpoint {
case .signIn:
return "/signIn"
}
}
}
In this way the asUrlRequest() function will be used throughout the code (; the Alamofire.Session().request() function will accept the each one of the routers.
Additionally, there is a great open-source abstraction that does similar work above Alamofire. Moya - https://github.com/Moya/Moya.
It supports Combine and RxSwift right out of the box
I'm trying to convert my AF request to Router structures for a cleaner project. I'm getting an error for:
Value of protocol type 'Any' cannot conform to 'Encodable'; only struct/enum/class types can conform to protocols.
Please help me to fix the code. THANK YOU!
My URL will have a placeholder for username and the password will be sent in body. The response will be Bool (success), username and bearer token.
Under is my AF request:
let username = usernameTextField.text
let password = passwordTextField.text
let loginParams = ["password":"\(password)"]
AF.request("https://example.com/users/\(username)/login",
method: .post,
parameters: loginParams,
encoder: JSONParameterEncoder.default,
headers: nil, interceptor: nil).response { response in
switch response.result {
case .success:
if let data = response.data {
do {
let userLogin = try JSONDecoder().decode(UsersLogin.self, from: data)
if userLogin.success == true {
defaults.set(username, forKey: "username")
defaults.set(password, forKey: "password")
defaults.set(userLogin.token, forKey: "token")
print("Successfully get token.")
} else {
//show alert
print("Failed to get token with incorrect login info.")
}
} catch {
print("Error: \(error)")
}
}
case .failure(let error):
//show alert
print("Failed to get token.")
print(error.errorDescription as Any)
}
}
What I have so far for converting to AF Router structures:
import Foundation
import Alamofire
enum Router: URLRequestConvertible {
case login(username: String, password: String)
var method: HTTPMethod {
switch self {
case .login:
return .post
}
}
var path: String {
switch self {
case .login(let username):
return "/users/\(username)/login"
}
}
var parameters: Parameters? {
switch self {
case .login(let password):
return ["password": password]
}
}
// MARK: - URLRequestConvertible
func asURLRequest() throws -> URLRequest {
let url = try Constants.ProductionServer.baseURL.asURL()
var request = URLRequest(url: url.appendingPathComponent(path))
// HTTP Method
request.httpMethod = method.rawValue
// Common Headers
request.setValue(ContentType.json.rawValue, forHTTPHeaderField: HTTPHeaderField.acceptType.rawValue)
request.setValue(ContentType.json.rawValue, forHTTPHeaderField: HTTPHeaderField.contentType.rawValue)
// Parameters
switch self {
case .login(let password):
request = try JSONParameterEncoder().encode(parameters, into: request) //where I got the error
}
return request
}
}
class APIClient {
static func login(password: String, username: String, completion: #escaping (Result<UsersLogin, AFError>) -> Void) {
AF.request(Router.login(username: username, password: password)).responseDecodable { (response: DataResponse<UsersLogin, AFError>) in
completion(response.result)
}
}
}
LoginViewController Class (where I replaced the AF.request code)
APIClient.login(password: password, username: username) { result in
switch result {
case .success(let user):
print(user)
case .failure(let error):
print(error.localizedDescription)
}
Codable UsersLogin model
struct UsersLogin: Codable {
let success: Bool
let username: String
let token: String?
enum CodingKeys: String, CodingKey {
case success = "success"
case username = "username"
case token = "token"
}
}
Took me a while but finally fixed it. I also clean up the code too.
enum Router: URLRequestConvertible {
case login([String: String], String)
var baseURL: URL {
return URL(string: "https://example.com")!
}
var method: HTTPMethod {
switch self {
case .login:
return .post
}
}
var path: String {
switch self {
case .login(_, let username):
return "/users/\(username)/login"
}
}
func asURLRequest() throws -> URLRequest {
print(path)
let urlString = baseURL.appendingPathComponent(path).absoluteString.removingPercentEncoding!
let url = URL(string: urlString)
var request = URLRequest(url: url!)
request.method = method
switch self {
case let .login(parameters, _):
request = try JSONParameterEncoder().encode(parameters, into: request)
}
return request
}
}
Usage
let username = usernameTextField.text
AF.request(Router.login(["password": password], username)).responseDecodable(of: UsersLogin.self) { (response) in
if let userLogin = response.value {
switch userLogin.success {
case true:
print("Successfully get token.")
case false:
print("Failed to get token with incorrect login info.")
}
} else {
print("Failed to get token.")
}
}
I solved a similar problem in this way. I created a protocol Routable
enum EncodeMode {
case encoding(parameterEncoding: ParameterEncoding, parameters: Parameters?)
case encoder(parameterEncoder: ParameterEncoder, parameter: Encodable)
}
protocol Routeable: URLRequestConvertible {
var baseURL: URL { get }
var path: String { get }
var method: HTTPMethod { get }
var encodeMode: EncodeMode { get }
}
extension Routeable {
// MARK: - URLRequestConvertible
func asURLRequest() throws -> URLRequest {
let url = baseURL.appendingPathComponent(path)
var urlRequest: URLRequest
switch encodeMode {
case .encoding(let parameterEncoding, let parameters):
urlRequest = try parameterEncoding.encode(URLRequest(url: url), with: parameters)
case .encoder(let parameterEncoder, let parameter):
urlRequest = URLRequest(url: url)
urlRequest = try parameterEncoder.encode(AnyEncodable(parameter), into: urlRequest)
}
urlRequest.method = method
return urlRequest
}
}
And my routers look like this one
enum WifiInterfacesRouter: Routeable {
case listActive(installationId: Int16?)
case insert(interface: WifiInterface)
var encodeMode: EncodeMode {
switch self {
case .listActive(let installationId):
guard let installationId = installationId else {
return .encoding(parameterEncoding: URLEncoding.default, parameters: nil)
}
return .encoding(parameterEncoding: URLEncoding.default, parameters: ["idInstallation": installationId])
case .insert(let interface):
return .encoder(parameterEncoder: JSONParameterEncoder.default, parameter: interface)
}
}
var baseURL: URL {
return URL(string: "www.example.com/wifiInterfaces")!
}
var method: HTTPMethod {
switch self {
case .listActive: return .get
case .insert: return .post
}
}
var path: String {
switch self {
case .listActive: return "listActive"
case .insert: return "manage"
}
}
}
To solve the build error
Protocol 'Encodable' as a type cannot conform to the protocol itself
I used the useful AnyCodable library. A type erased implementation of Codable.
You can't use Parameters dictionaries with Encodable types, as a dictionary of [String: Encodable] is not Encodable, like the error says. I suggest moving that step of the asURLRequest process into a separate function, such as:
func encodeParameters(into request: inout URLRequest) {
switch self {
case let .login(parameters):
request = try JSONParameterEncoder().encode(parameters, into: request)
}
}
Unfortunately this doesn't scale that well for routers with many routes, so I usually break up my routes into small enums and move my parameters into separate types which are combined with the router to produce the URLRequest.
For many of my endpoints, I require a bearer token to be passed with the request to authenticate the user. Because of that, I also need to refresh the user's token if it expires.
I found this question to start me along, but I'm still unsure about some things and how to implement them.
As the answer to the question above suggests, I've created an extension for MoyaProvider:
extension MoyaProvider {
convenience init(handleRefreshToken: Bool) {
if handleRefreshToken {
self.init(requestClosure: MoyaProvider.endpointResolver())
} else {
self.init()
}
}
static func endpointResolver() -> MoyaProvider<Target>.RequestClosure {
return { (endpoint, closure) in
//Getting the original request
let request = try! endpoint.urlRequest()
//assume you have saved the existing token somewhere
if (#tokenIsNotExpired#) {
// Token is valid, so just resume the original request
closure(.success(request))
return
}
//Do a request to refresh the authtoken based on refreshToken
authenticationProvider.request(.refreshToken(params)) { result in
switch result {
case .success(let response):
let token = response.mapJSON()["token"]
let newRefreshToken = response.mapJSON()["refreshToken"]
//overwrite your old token with the new token
//overwrite your old refreshToken with the new refresh token
closure(.success(request)) // This line will "resume" the actual request, and then you can use AccessTokenPlugin to set the Authentication header
case .failure(let error):
closure(.failure(error)) //something went terrible wrong! Request will not be performed
}
}
}
}
I've also created an extension for TargetType, which looks like this:
import Moya
public protocol TargetTypeExtension: TargetType, AccessTokenAuthorizable {}
public extension TargetTypeExtension {
var baseURL: URL { return URL(string: Constants.apiUrl)! }
var headers: [String: String]? { return nil }
var method: Moya.Method { return .get }
var authorizationType: AuthorizationType { return .bearer }
var sampleData: Data { return Data() }
}
Here is one such implementation of it:
import Moya
public enum Posts {
case likePost(postId: Int)
case getComments(postId: Int)
}
extension Posts: TargetTypeExtension {
public var path: String {
switch self {
case .likePost(_): return "posts/like"
case .getComments(_): return "posts/comments"
}
}
public var authorizationType: AuthorizationType {
switch self {
case .likePost(_): return .bearer
case .getComments(_): return .none
}
}
public var method: Moya.Method {
switch self {
case .likePost, .getComments:
return .post
}
}
public var task: Task {
switch self {
case let .likePost(postId):
return .requestParameters(parameters: ["postId": postId], encoding: JSONEncoding.default)
case let .getComments(postId):
return .requestParameters(parameters: ["postId": postId], encoding: JSONEncoding.default)
}
}
}
As you can see, my likePost request requires a bearer token, while my getComments request does not.
So I have a few questions:
How would I modify my MoyaProvider extension to utilize Moya's AccessTokenPlugin, found here?
How would I modify my MoyaProvider extension to NOT require a bearer token if the AuthorizationType is .none for a specific request?
Thanks!
I did with custom moya provider and RxSwift if you are using RxSwift you can take reference, it will not directly fit into yor code!!
extension Reactive where Base: MyMoyaProvider {
func request(_ token: Base.Target, callbackQueue: DispatchQueue? = nil) -> Single<Response> {
return Single.create { [weak base] single in
var pandingCancelable:Cancellable?
/// reschedule original request
func reschedulCurrentRequest() {
base?.saveRequest({
pandingCancelable = base?.request(token, callbackQueue: callbackQueue, progress: nil) { result in
switch result {
case.success(let response):
single(.success(response))
case .failure(let error):
single(.error(error))
}
}
})
}
func refreshAccessToken(refreshToken:String) -> Cancellable? {
base?.isRefreshing = true /// start retrieveing refresh token
return base?.request(.retriveAccessToken(refreshToken: refreshToken), completion: { _ in
base?.isRefreshing = false /// end retrieveing refresh token
base?.executeAllSavedRequests()
})
}
if (base?.isRefreshing ?? false) {
reschedulCurrentRequest()
return Disposables.create { pandingCancelable?.cancel() }
}
let cancellableToken = base?.request(token, callbackQueue: callbackQueue, progress: nil) { result in
switch result {
case let .success(response):
if !(base?.isRefreshing ?? false), !token.isOAuth2TokenRefreshType, response.statusCode == TokenPlugin.CODE_UNAUTHORIZED, let refreshToken = token.getRefreshToken {
reschedulCurrentRequest()
_ = refreshAccessToken(refreshToken: refreshToken)
} else if (base?.isRefreshing ?? false) {
reschedulCurrentRequest()
} else {
single(.success(response))
}
case let .failure(error):
single(.error(error))
}
}
return Disposables.create {
cancellableToken?.cancel()
}
}
}
}
CustomProvider:
class MyMoyaProvider: MoyaProvider<MyServices> {
var isRefreshing = false
private var pandingRequests: [DispatchWorkItem] = []
func saveRequest(_ block: #escaping () -> Void) {
// Save request to DispatchWorkItem array
pandingRequests.append( DispatchWorkItem {
block()
})
}
func executeAllSavedRequests() {
pandingRequests.forEach({ DispatchQueue.global().async(execute: $0); })
pandingRequests.removeAll()
}
}
extension TargetType {
var isOAuth2TokenRefreshType: Bool { return false }
var getRefreshToken:String? { return nil }
}
So I'm writing my networking code using a router design pattern. I'm writing a new router for different components of my app (should i be doing this? I try to limit my objects lines of code). Heres my router enum. If I was using a class, I could define a method once to populate variables like HTTPMethod and override them if necessary. Is there a way to do this with enums? Is it worth implementing or should i repeat the same code. There are a few other places besides httpMethod such as URL construction where I think this could be helpful.
I was thinking i could do something with protocols but am not sure if I'm wasting my time.
enum PRRouter: URLRequestConvertible {
static let baseURLString = "http://localhost:8000/"
case get(Int)
case create([String : Any])
case delete(Int)
func asURLRequest() throws -> URLRequest {
var method: HTTPMethod{
switch self {
case .get:
return .get
case .create:
return .post
case.delete:
return .delete
}
}
let params : ([String : Any]?) = {
switch self {
case .get, .delete:
return nil
case .create(let newTodo):
return newTodo
}
}()
let url : URL = {
let relativePath: String?
switch self{
case .get(let number):
relativePath = "test/\(number)"
case .create:
relativePath = "test/"
case .delete:
relativePath = "test/"
}
var url = URL(string: PRRouter.baseURLString)!
if let relativePath = relativePath {
url = url.appendingPathComponent(relativePath)
}
return url
}()
var urlRequest = URLRequest(url:url)
urlRequest.httpMethod = method.rawValue
let encoding = JSONEncoding.default
return try encoding.encode(urlRequest, with: params)
}
Make the enum conform to a protocol with a default implementation.
protocol P {
func f()
}
extension P {
func f() { print("default implementation") }
}
enum E: P {
case Foo
}
let e = E.Foo
e.f()
I do something similar in my own project. Here is an example based on your code to get you started:
protocol APIProtocol {
var path: String { get }
var method: HTTPMethods { get }
var bodyParameters: [String: Any?]? { get }
}
enum HTTPMethods: String {
case get = "GET"
case post = "POST"
}
enum PRRouter: APIProtocol {
case get(Int)
case create([String : Any])
case delete(Int)
var path: String {
switch self {
case let .get(number):
return "test/\(number)"
default:
return "test"
}
}
var method: HTTPMethods {
return .get
}
var bodyParameters: [String : Any?]? {
return nil
}
}
extension APIProtocol {
func execute(completion: #escaping ((Data?) -> Void)) -> URLSessionDataTask? {
guard let url = URL(string: "http://localhost:8000/\(path)") else { return nil }
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = method.rawValue
if let bodyParameters = bodyParameters {
urlRequest.httpBody = try? JSONSerialization.data(withJSONObject: bodyParameters, options: [.prettyPrinted])
}
let task = URLSession.shared.dataTask(with: urlRequest) { (data, urlResponse, error) in
completion(data)
}
task.resume()
return task
}
}
Finally you can use it like this:
let dataTask = PRRouter.get(2).execute { (data) in
//
}
You could extend this further by changing the completion block in the execute function to return a deserialized object.
I'm using Moya for handling communication between my swift application and api, I'm able to post and get data but unable to post file to api server, following is my code
enum TestApi {
...
case PostTest(obj: [String: AnyObject])
...
}
extension TestApi: TargetType {
var baseURL: NSURL {
switch self {
case .PostTest:
return NSURL(string: "http://192.168.9.121:3000")!
}
}
var path: String {
switch self {
case .PostTest:
return "/api/file"
}
}
var method: Moya.Method {
switch self {
case .PostTest:
return .POST
}
}
var parameters: [String: AnyObject]? {
switch self {
case .PostTest(let obj):
return ["image": obj["image"]!]
}
}
var sampleData: NSData {
return "".dataUsingEncoding(NSUTF8StringEncoding)!
}
var multipartBody: [MultipartFormData]? {
switch self {
case .PostTest(let multipartData):
guard let image = multipartData["image"] as? [NSData] else { return[] }
let formData: [MultipartFormData] = image.map{MultipartFormData(provider: .Data($0), name: "images", mimeType: "image/jpeg", fileName: "photo.jpg")}
return formData
default:
return []
}
}
}
and following is the way I called
return testApiProvider.request(.PostTest(obj: _file)).debug().mapJSON().map({ JSON -> EKResponse? in
return Mapper<EKResponse>().map(JSON)
})
I dont receive no response and no hit was sent to the api server
Multipart body is deprecated in Moya 8.0.0. Instead of that use Task for uploading.
Check this issue:
Moya multipart upload target
the subscription is missing in the calling code. This is not really a Moya problem, but problem with Reactive Extensions. the following .subscribeNext { _ in } fixed my issue
return testApiProvider
.request(.PostTest(obj: _file))
.debug()
.mapJSON()
.map({ JSON -> EKResponse? in
return Mapper<EKResponse>().map(JSON)
})
.subscribeNext { _ in }