Refactoring Code in Swift - swift

I have a pretty standard problem here that I am a little confused how to make more elegant in the swift tradition of things.
I have a base URL string in my APIClient, a path for different methods to use, and methods might pass in a optional string.
How do I write this such that it is much cleaner? I feel like I am writing swift code but not using any of the new constructs (like guard, let), etc.
// call the API
ApiClient.sharedInstance.getUser("56cfffce227a6c2c9b000001", successCompletion: successCompletion, failureCompletion: failureCompletion)
// setting the current URL
let currentURL = String("http://localhost:3000")
// class definition
class ApiClient {
var baseURL:String!;
// have to init the string class for the
init (base:String){
self.baseURL = base
}
class var sharedInstance: ApiClient {
struct Static{
static let instance = ApiClient(base: currentURL)
}
return Static.instance
}
func getUser(user_id: String?, successCompletion: ResultHandler<User>, failureCompletion:ResultHandler<FailureReason>){
// this is awkward
var url: URLStringConvertible!
// this is even more awkward
if user_id != nil {
url = "\(currentURL)/users/\(user_id!).json"
} else {
url = "\(currentURL)/users/me"
}
}
}

Cleaned some things up and removed some unnecessary forced-unwraps.
class ApiClient {
var baseURL: String;
// have to init the string class for the
init (base:String){
self.baseURL = base
}
class var sharedInstance: ApiClient {
struct Static{
static let instance = ApiClient(base: currentURL)
}
return Static.instance
}
func getUser(user_id: String?, successCompletion: ResultHandler<User>, failureCompletion:ResultHandler<FailureReason>){
var url: URLStringConvertible
if let user_id = user_id {
url = "\(currentURL)/users/\(user_id!).json"
}
else{
url = "\(currentURL)/users/me"
}
}
Depending on what you're doing in getUser, things could be done differently.
FYI, what I tend to do for singletons: (arguably not the best):
private static var realSharedInstance: Class?
static var sharedInstance: Class {
get {
if let realSharedInstance = realSharedInstance {
return realSharedInstance
}
else{
realSharedInstance = Class()
return realSharedInstance!
}
}
}

For me, I like to create an Endpoint for every endpoint that the API supports. In this case, a UsersEndpoint which can make requests via APIClient.
This is easier to scale (for me) when there more endpoints and each endpoint has multiple resources.
Use in code:
MyAPI.sharedInstance.users.getUser(id, parameters: params, success: {}, failure: {})
MyAPI.sharedInstance.anotherEndpoint.doSomething(parameters: params, success: {}, failure: {})
The classes:
class MyAPI {
static let sharedInstance = MyAPI()
let users: UsersEndpoint
// more endpoints here
init() {
users = UsersEndpoint()
// ....
}
}
class APIClient {
static let sharedClient = APIClient()
var manager : Alamofire.Manager!
var baseURL: String
init() {
baseURL = String(format: "https://%#%#", self.instanceUrl, API.Version)
}
func get(endpoint endpoint: String,
parameters: [String:AnyObject],
success: SuccessCallback,
failure: FailureCallback) {
let requestUrl = NSURL(string: "\(self.baseURL)\(endpoint)")!
manager.request(.GET, requestUrl, parameters: parameters, headers: headers)
.validate()
.responseData { response in
switch response.result {
case .Success(let value):
if let data: NSData = value {
success(data: data)
log.verbose("Success - GET requestUrl=\(requestUrl)")
}
break;
case .Failure(let error):
failure(error: error)
log.error("Failure - GET requestUrl=\(requestUrl)\nError = \(error.localizedDescription)")
break;
}
}
}
}
class APIFacade {
var endpoint: String
init(endpoint: String) {
self.endpoint = endpoint;
}
func get(endpoint endpoint: String,
parameters: [String:AnyObject],
success: SuccessCallback,
failure: FailureCallback) {
APIClient.sharedClient.get(endpoint: endpoint, parameters: parameters, success: success, failure: failure)
}
}
class UsersEndpoint: APIFacade {
init() {
super.init(endpoint: "/users")
}
func getUser(id: String, parameters: [String:AnyObject], success: SuccessCallback, failure: FailureCallback) {
super.get(endpoint: "\(self.endpoint)/\(id)", parameters: parameters, success: success, failure: failure)
}
}

Related

How add page for pagination in protocol oriented networking

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.

How to implement multiple Routers with similar asURLRequest()

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

How can I use Alamofire Router to organize the API call? [swift/ Alamofire5]

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.

Refreshing bearer token and using AccessTokenPlugin

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 }
}

Error when tried to translate simple Alamofire request to Moya

I am trying to improve Network layer, so I used Moya in order to create a more scalable code.
I have a simple request method (with Alamofire) that requests a JSON object (I'm using this theMovieDB api as an example. So, this is the working code:
class Endpoints{
func getGenres(callback: #escaping (NSDictionary?)->()){
let headers = [
"Authorization": "Bearer 1234556789123345",
"Content-Type": "application/json;charset=utf-8"
]
let parameters: [String: String] = ["api_key": "1234567890"]
let url = "https://api.themoviedb.org/3/genre/movie/list?"
Alamofire.request(url, method: .get, parameters: parameters, headers: headers).responseJSON{ (response:DataResponse<Any>) in
switch(response.result) {
case .success(_):
if response.result.value != nil{
let t: NSDictionary = response.result.value as! NSDictionary
callback(t)
}
break
case .failure(_):
print(response.result.error!)
callback(nil)
break
}
}
}
The code above works totally fine, but I want to code the Moya equivalent structure, so I have this, strongly inspired in the documentation:
import Foundation
import Moya
enum MyService {
case getGenres
}
// MARK: - TargetType Protocol Implementation
extension MyService: TargetType {
var baseURL: URL { return URL(string:
"https://api.themoviedb.org/3")! }
var path: String {
switch self {
case .getGenres:
return "/genre/movie/list?"
}
}
var method: Moya.Method {
switch self {
case .getGenres:
return .get
}
}
var parameters: [String: Any]? {
switch self {
case .getGenres:
return ["api_key": "1234567890"]
}
}
var parameterEncoding: ParameterEncoding {
switch self {
case .getGenres:
return JSONEncoding.default
}
}
var sampleData: Data {
switch self {
case .getGenres:
return "".utf8Encoded
}
}
var task: Task {
switch self {
case .getGenres:
return .request
}
}
var headers: [String: String]? {
return [
"Authorization": "Bearer 1234556789123345",
"Content-Type": "application/json;charset=utf-8"
]
}
}
// MARK: - Helpers
private extension String {
var urlEscaped: String {
return self.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
}
var utf8Encoded: Data {
return self.data(using: .utf8)!
}
}
When using Moya service:
let provider = MoyaProvider<MyService>()
provider.request(.getGenres) { (result) in
print(result)
}
I always get a 504 or timeout response when using Moya services.
Any ideas?