api.ezedev.ru - это бесплатная площадка для тренировки выполнения сетевых запросов на языке Swift. Ниже представлено описание методов сервиса, а также примеры выполнения запросов с использованием различных инструментов. Площадка будет расти и дополняться новыми методами и примерами. Скачать готовый код можно тут.
/makeHandshake - простой метод для "рукопожатия" с сервером.
/messages - отправка данных на сервер в POST-запросе и получение этих данных в виде комбинированной строки.
/login - авторизация по номеру телефона и паролю. В ответе приходит токен, необходимый для выполнения запросов из категории authorized. В настоящий момент доступен только один статичный пользователь: 79876543210, qwerty.
/current_profile - получение текущего профиля пользователя. В хедер запроса нужно поместить токен, полученный в запросе авторизации.
struct HandshakeData: Decodable {
let message: String
}
func makeHandshake() {
let url = URL(string: "https://api.ezedev.ru/makeHandshake")!
let request = URLRequest(url: url)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let data, let handshake = try? JSONDecoder().decode(HandshakeData.self, from: data) {
print(handshake.message)
} else {
print("Error =)")
}
}
task.resume()
}
struct PostMessageData: Encodable {
let firstname: String
let lastname: String
let age: Int
let weight: Double
}
struct PostMessageResponse: Decodable {
let success: Bool
let message: String?
let error: String?
}
func postMessage(firstname: String, lastname: String, age: Int, weight: Double) {
let url = URL(string: "https://api.ezedev.ru/messages")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let message = PostMessageData(firstname: firstname, lastname: lastname, age: age, weight: weight)
let messageData = try? JSONEncoder().encode(message)
request.httpBody = messageData
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let data, let postResponse = try? JSONDecoder().decode(PostMessageResponse.self, from: data) {
print(postResponse.message ?? "")
} else {
print("Error =)")
}
}
task.resume()
}
func login(phone: String, password: String, completion: @escaping (String?) -> Void) {
let url = URL(string: "https://api.ezedev.ru/login")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
let body = "phone=\(phone)&password=\(password)".data(using: .utf8)
request.httpBody = body
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let data, let loginData = try? JSONDecoder().decode(LoginResponseData.self, from: data) {
print(loginData.accessToken)
completion(loginData.accessToken)
} else {
print("Error =)")
}
}
task.resume()
}
struct LoginResponseData: Codable {
let accessToken, tokenType: String
enum CodingKeys: String, CodingKey {
case accessToken = "access_token"
case tokenType = "token_type"
}
}
login(phone: "79876543210", password: "qwerty") { token in
self.token = token ?? ""
}
var token: String = ""
func getProfile() {
let url = URL(string: "https://api.ezedev.ru/current_profile")!
var request = URLRequest(url: url)
let tokenHeaderValue = "Bearer \(token)"
request.setValue(tokenHeaderValue, forHTTPHeaderField: "Authorization")
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let data, let profile = try? JSONDecoder().decode(ProfileData.self, from: data) {
print(profile.name)
print(profile.age)
} else {
print("Error =)")
}
}
task.resume()
}
struct ProfileData: Decodable {
let name: String
let age: Int
}
login(phone: "79876543210", password: "qwerty") { token in
self.token = token ?? ""
self.getProfile()
}
import Foundation
import Moya
enum APIType {
case makeHandshake
case messages(PostMessageData)
case login(String, String)
case currentProfile
static var provider = MoyaProvider<Self>()
}
extension APIType: TargetType, AccessTokenAuthorizable {
var baseURL: URL {
URL(string: "https://api.ezedev.ru")!
}
var path: String {
switch self {
case .makeHandshake:
return "/makeHandshake"
case .messages:
return "/messages"
case .login:
return "/login"
case .currentProfile:
return "/current_profile"
}
}
var method: Moya.Method {
switch self {
case .makeHandshake:
return .get
case .messages:
return .post
case .login:
return .post
case .currentProfile:
return .get
}
}
var task: Moya.Task {
switch self {
case .makeHandshake:
return .requestPlain
case .messages(let value):
return .requestJSONEncodable(value)
case .login(let phone, let password):
return .requestParameters(
parameters: [
"phone": phone,
"password": password
],
encoding: URLEncoding.default
)
case .currentProfile:
return .requestPlain
}
}
var headers: [String: String]? {
nil
}
var authorizationType: AuthorizationType? {
switch self {
case .currentProfile:
return .bearer
default:
return nil
}
}
}
import Moya
public struct MoyaService {
let provider: MoyaProvider<APIType>
init(accessToken: String) {
self.provider = .init(
plugins: [
AccessTokenPlugin(
tokenClosure: { _ in
return accessToken
}
)
]
)
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
makeHandshake()
postMessage(firstname: "eze", lastname: "dev", age: 1, weight: 1.5)
login(phone: "79876543210", password: "qwerty") { token in
self.token = token
self.getProfile()
}
}
var token: String? = ""
func makeHandshake() {
let moyaService = MoyaService(accessToken: "")
moyaService.provider.request(.makeHandshake) { result in
switch result {
case .success(let response):
if let value = try? JSONDecoder().decode(HandshakeData.self, from: response.data) {
print(value.message)
}
case .failure(let error):
print(error)
}
}
}
func postMessage(firstname: String, lastname: String, age: Int, weight: Double) {
let data = PostMessageData(firstname: firstname, lastname: lastname, age: age, weight: weight)
let moyaService = MoyaService(accessToken: "")
moyaService.provider.request(.messages(data)) { result in
switch result {
case .success(let response):
if let value = try? JSONDecoder().decode(PostMessageResponse.self, from: response.data) {
print(value.message ?? "")
}
case .failure(let error):
print(error)
}
}
}
func login(phone: String, password: String, completion: @escaping (String?) -> Void) {
let moyaService = MoyaService(accessToken: "")
moyaService.provider.request(.login(phone, password)) { result in
switch result {
case .success(let response):
if let response = try? JSONDecoder().decode(LoginResponseData.self, from: response.data) {
completion(response.accessToken)
}
case .failure(let error):
print(error)
}
}
}
func getProfile() {
guard let token else { return }
let moyaService = MoyaService(accessToken: token)
moyaService.provider.request(.currentProfile) { result in
switch result {
case .success(let response):
if let response = try? JSONDecoder().decode(ProfileData.self, from: response.data) {
print(response.name)
print(response.age)
}
case .failure(let error):
print(error)
}
}
}
}