Last active
June 13, 2018 20:26
-
-
Save ARamy23/928f4e7b72f0ac7a3d2da57f91d82cba to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
import Alamofire | |
protocol URLRequestBuilder: URLRequestConvertible { | |
var mainURL: URL { get } | |
var requestURL: URL { get } | |
// MARK: - Path | |
var path: ServerPaths { get } | |
var headers: HTTPHeaders { get } | |
// MARK: - Parameters | |
var parameters: Parameters? { get } | |
// MARK: - Methods | |
var method: HTTPMethod { get } | |
var encoding: ParameterEncoding { get } | |
var urlRequest: URLRequest { get } | |
var deviceId: String { get } | |
} | |
extension URLRequestBuilder { | |
var mainURL: URL { | |
//1 | |
switch AppEnvironement.currentState { | |
case .development: | |
return URL(string: "https://staging.mysite.com")! | |
default: | |
return URL(string: "https://www.mysite.com")! | |
} | |
} | |
//2 | |
var requestURL: URL { | |
return mainURL.appendingPathComponent(path.rawValue) | |
} | |
var headers: HTTPHeaders { | |
var header = HTTPHeaders() | |
if let token = KeyChain.userToken { | |
header["Authorization"] = "Bearer \(token)" | |
} | |
return header | |
} | |
var defaultParams: Parameters { | |
var param = Parameters() | |
param["app_lang"] = AppEnvironement.currentLang ?? "en" | |
param["mobile_id"] = deviceId | |
return param | |
} | |
var encoding: ParameterEncoding { | |
switch method { | |
case .get: | |
return URLEncoding.default | |
default: | |
return JSONEncoding.default | |
} | |
} | |
var urlRequest: URLRequest { | |
var request = URLRequest(url: requestURL) | |
request.httpMethod = method.rawValue | |
headers.forEach { request.addValue($1, forHTTPHeaderField: $0) } | |
return request | |
} | |
var deviceId: String { | |
return UIDevice.current.identifierForVendor?.uuidString ?? "" | |
} | |
func asURLRequest() throws -> URLRequest { | |
return try encoding.encode(urlRequest, with: parameters) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment