Skip to content

Instantly share code, notes, and snippets.

@bishalg
Created November 11, 2016 08:28
Show Gist options
  • Save bishalg/4d554cd79a138c43c00c17cebf6eb3d3 to your computer and use it in GitHub Desktop.
Save bishalg/4d554cd79a138c43c00c17cebf6eb3d3 to your computer and use it in GitHub Desktop.
URLRequest Router for Alamofire URLRequestConvertible Swift 3.0
//
// Created by Bishal Ghimire on 11/6/16.
// Copyright © 2016 bigBsoft. All rights reserved.
//
import Foundation
import Alamofire
enum ActivitiesDate {
case currentDay // Activities Current Day
case pastDay(day: String) // Activities Past Day
case currentWeek // Activities Current Week
case pastWeek(week: String) // Activities Past Week
case recentMonth // Activities Most Recent 30 Days
case pastMonth(month: String) // Activities Past Month
func param() -> String {
switch self {
case .currentDay:
return "day=current"
case .pastDay(let day):
return "day=\(day)"
case .currentWeek:
return "week=current"
case .pastWeek(let week):
return "week=\(week)"
case .recentMonth:
return "month=current"
case .pastMonth(let month):
return "month=\(month)"
}
}
}
enum ActivitieRouter: URLRequestConvertible {
case activitiesIndex // Activities Index
case activityDate(activitiesDate: ActivitiesDate)
case getActivity(activityID: Int) // Get Activity
case createActivities(param: Parameters) // Create Activities
case updateActivity(activityID: Int, param: Parameters) // Update Activity
case destoryActivity(activityID: Int) // Destroy Activity
// static let baseURLString = NetworkManager.baseURL + "activities/"
var method: HTTPMethod {
switch self {
case .activitiesIndex:
return .get
case .activityDate:
return .get
case .getActivity:
return .get
case .createActivities:
return .post
case .updateActivity:
return .put
case .destoryActivity:
return .delete
}
}
var path: String {
let subPath = "activities"
switch self {
case .activitiesIndex:
return subPath
case .activityDate(let activitiesDate):
return subPath + "?" + activitiesDate.param()
case .getActivity(let activityID):
return subPath + "?" + "\(activityID)"
case .createActivities:
return subPath
case .updateActivity(let activityID, _):
return subPath + "?" + "\(activityID)"
case .destoryActivity(let activityID):
return subPath + "?" + "\(activityID)"
}
}
// MARK: URLRequestConvertible
func asURLRequest() throws -> URLRequest {
var urlRequest = NetworkManager.getTokenRequest(path)
urlRequest.httpMethod = method.rawValue
switch self {
case .createActivities(let parameters):
urlRequest = try URLEncoding.default.encode(urlRequest, with: parameters)
case .updateActivity(_, let parameters):
urlRequest = try URLEncoding.default.encode(urlRequest, with: parameters)
default:
break
}
return urlRequest
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment