Skip to content

Instantly share code, notes, and snippets.

@leojkwan
Created February 20, 2017 22:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leojkwan/ebd3f3e13ac5af456ee42ad817ab1820 to your computer and use it in GitHub Desktop.
Save leojkwan/ebd3f3e13ac5af456ee42ad817ab1820 to your computer and use it in GitHub Desktop.
import UIKit
import Moya
class ViewController: UIViewController {
private let instaFoodProvider = MoyaProvider<InstaFoodService>()
override func viewDidLoad() {
super.viewDidLoad()
instaFoodProvider.request(.createUser(firstName: "Leo", lastName: "Kwan")) { (result) in
switch result {
case .success(let response):
// let data = response.data
// let statusCode = response.statusCode
// Or you can use this wrapper from Moya
// convenient method to filter status codes from 200-399
do {
try response.filterSuccessfulStatusCodes()
let data = try response.mapJSON()
print(data)
} catch let error{
print(error)
}
case .failure(let error): break
print(error)
}
}
}
}
// InstaFood Service APIManager ... Moya-Style
enum InstaFoodService {
case createUser(firstName: String, lastName: String)
}
extension InstaFoodService: TargetType {
var baseURL: URL {
return URL(string: "https://api.instafood.com")!
}
var path: String {
switch self {
case .createUser(_, _):
return "/user/"
}
}
var method: Moya.Method {
switch self {
case .createUser:
return .get
}
}
var task: Task {
switch self {
case .createUser:
return .request
}
}
var parameters: [String: Any]? {
switch self {
case .createUser(let firstName, let lastName):
return ["first_name": firstName, "last_name": lastName]
}
}
var parameterEncoding: ParameterEncoding {
switch self {
case .createUser:
// Send parameters as JSON in request body
return JSONEncoding.default
}
}
var sampleData: Data {
switch self {
case .createUser(let firstName, let lastName):
let userJson = [
"firstName": firstName,
"lastName": lastName
]
return jsonSerializedUTF8(json: userJson)
}
}
private func jsonSerializedUTF8(json: [String: Any]) -> Data {
return try! JSONSerialization.data(withJSONObject: json, options: [.prettyPrinted])
}
}
struct User {
let firstName: String
let lastName: String
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment