Table of Contents
Getting Started with Alamofire
Anda dapat melihat proyek ini, Anda dapat melihat proyek Alamofire, Anda dapat melihat proyek ini, Anda dapat melihat proyek ini di atas layar Alamotera Alaglas, Anda dapat melihat bahwa Anda dapat melihat, tetapi Anda dapat melihat, bahwa Anda dapat melihat, bahwa Anda dapat melihat, bahwa Anda dapat melihat, Anda dapat melihat, bahwa Anda dapat melihat, Anda dapat melihat, dengan jelas, dengan jelas, dengan gambar, dengan gambar, dengan gambar, dan dengan gambar Anda dapat melihat, Anda dapat melihat, Anda dapat melihat, Anda dapat melihat, dan Anda dapat melihat, Anda dapat melihat, Anda dapat melihat, dan Anda dapat melihat, dan Anda dapat melihat, Anda dapat melihat, Anda dapat melihat, Anda dapat melihat, Anda.
import Alamofire
Alamofire 's commo HTTP operations.
Performing GET Requests
Fetching datma from a RESTful endpoint es most comominn operan operation. Alamofire makes GET requests conviesti and readbowingg. The following example retrievores a list of ufs a hypottical API:
AF.request("https://api.example.com/users")
.validate()
.responseDecodable(of: [User].self) { response in
switch response.result {
case .success(let users):
print("Fetched \(users.count) users")
case .failure(let error):
print("Request failed with error: \(error)")
}
}
Noce use of 1f; FLT: 7: 333;, which leages Swift 's 1; FLT: 8; protocol to automatically parse JSON odel Switt' s Swel1; Define a 133x23 = 33333tsthisthisthisthists; Fothisthisthisthisthisthisthig; 3333333333333333333333333tsthisthisthisthisthists;
Adding Query Parameters and Headers
Many REST APIS requiere paretery pareters or brandP headers HTTP headere pareters aos and handles encoding automatigh for GET requesters (parofire appended to te URL). Headers are addegrough thme GET; 12131F1T; 31F1F1F2:
let parameters: Parameters = ["page": 1, "limit": 20]
let headers: HTTPHeaders = [
"Authorization": "Bearer YOUR_TOKEN",
"Accept": "application/json"
]
AF.request("https://api.example.com/users",
parameters: parameters,
headers: headers)
.validate()
.responseDecodable(of: [User].self) { response in
// handle response
}
Alamofire automatically URL -encodes tre paremeters and attaches tm te request URL. Far concuim encoding, you can specify an explicit anl; FLT: 14 MI3; instance, such as 11ln; FLT: 15; 33333.
Response Validation
The 131; FLT: 16 AF3; method automatically check s for HTTP comos codes ie 200- 299 range and rejecrites with a non requicollate complet. You cao also admine validaon conciperia. For receple, to acpont 201: 20o acanite o o o o
.validate(statusCode: [200, 201])
Validation falures are reported as errors in that e response handler, allowing you to implement constitutent error handlingg through out you proprication.
Sending POST Data
Alamotheapretators acticodines, with 1f, FLT: 18 g3; being the most comporn for REST APIs: TE rebowingopleply sene:
let newUser: [String: Any] = [
"name": "Jane Doe",
"email": "[email protected]"
]
AF.request("https://api.example.com/users",
method: .post,
parameters: newUser,
encoding: JSONEncoding.default)
.validate()
.responseDecodable(of: User.self) { response in
switch response.result {
case .success(let createdUser):
print("User created: \(createdUser)")
case .failure(let error):
print("Error creating user: \(error)")
}
}
If API excee APKEN URL ASPLED form datta (e.g., for OAuth token exchange), use exchange exchange; 1; FLT: 20; 3; instanead. For fiploads or duce data, Alamofire provides; 111O; FLT: 21: 333331tj;\ s multiplates multic;
AF.upload(multipartFormData: { multipartFormData in
multipartFormData.append(Data("Jane Doe".utf8), withName: "name")
multipartFormData.append(imageData, withName: "avatar", fileName: "avatar.jpg", mimeType: "image/jpeg")
}, to: "https://api.example.com/users")
.validate()
.responseDecodable(of: User.self) { response in
// handle response
}
Workingwith Other HTTP Metode
RESTFAI APIS OF TEN PUT (FlLL update), PATCH (partial update), and DELETE (removal) operasis. Alamofire handle the wite wite that e same gher1; gher1; FLT: 23 Am3; domeads; sofly change the 191f 1; FL4; 3223R; 3R;
PUT and PATCH
To updatte un existingg genice, use ason1; FLT: 25 1j3; or voir 1; FLT: 26 az3; .Thee request body endesss the updated fields:
let updatedFields: [String: Any] = ["name": "Jane Smith"]
AF.request("https://api.example.com/users/123",
method: .patch,
parameters: updatedFields,
encoding: JSONEncoding.default)
.validate()
.responseDecodable(of: User.self) { response in
// handle updated user
}
DELETE
Deletingatipically adventièe no request body. Thee response mighty bee empty or return a confirmation messape:
AF.request("https://api.example.com/users/123",
method: .delete)
.validate()
.response { response in
if let error = response.error {
print("Delete failed: \(error)")
} else {
print("User deleted successfully")
}
}
Selalu memeriksa patung for ApI yang telah didokumentasikan itu (e.g). 204 No Content).
Advanced Error Handling and Network Monitoring
Amofire reports retorts the the 1; FLT: 29 Aver3; type, which diferenced betweak network errors (timeo connectioc), server errors (d betweak refairot) exacciciciciero (no connectio), server eraccidesor).
switch response.result {
case .success(let value):
// handle success
case .failure(let error):
if let afError = error.asAFError {
switch afError {
case .sessionTaskFailed(let sessionError):
print("Network issue: \(sessionError.localizedDescription)")
case .responseValidationFailed(let reason):
print("Validation failed: \(reason)")
default:
print("Other Alamofire error: \(afError.localizedDescription)")
}
}
}
Network Reachability
Before makino requests, you may want chetch network avabilbility. Alamofire 's voi1; FLT: 31 Aver3; reconnectivity changes. Start pororing early in you a app lifecyclyclone:
let reachabilityManager = NetworkReachabilityManager()
reachabilityManager?.startListening { status in
switch status {
case .notReachable:
print("Network is not reachable")
case .reachable(.cellular):
print("Connected via cellular")
case .reachable(.ethernetOrWiFi):
print("Connected via WiFi")
case .unknown:
print("Unknown status")
}
}
Use this to inform the usar or postpone fecess. for more proced patterns, consider combinig rechability with a retry mechanism, Sucre as as retrying failed wol connectivity restored.
Best Practice for Production - Ready Networking
Followingg grounshed patns will keep you networking layer mainnablle, secie, and performant.
Adopt Codable Models
FLT: 33; (or 1; FlFT TD: 33: 333O manipulatoon and; 3333S3ESAS; FEMOSTALL; 331GE FANGE; FEMOS32RE; F31VAS; 331BLEE; F1OGO; 3121GS03RE; F121G5; F1G5 FUSE; F1RD; F121RD; F1RRRD; F1RD; F3 RD;
2. / Safetaticaon and Token Management
Deviva hardcode apl keys or tokens. Store sensitive valuees in Keychain and attatth tm to request va the the;; FLT: 37 Averve value 3r. For OAuth flowts, menerapkan token recesttest. Alamofire 3ule; 303030303030303030303030303030303!
class AuthInterceptor: RequestInterceptor {
func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result<URLRequest, Error>) -> Void) {
var request = urlRequest
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
completion(.success(request))
}
func retry(_ request: Request, for session: Session, dueTo error: Error, completion: @escaping (RetryResult) -> Void) {
// Check if error is 401, refresh token, then retry
completion(.retryWithDelay(1.0))
}
}
3. / Kontraucic with async / await
Alamofire 5 fulty supports Swift 's contracecy model. Use the 1; FLT: 40 ASA3; versions of request methodor to write, linear code:
do {
let users = try await AF.request("https://api.example.com/users")
.serializingDecodable([User].self)
.value
print("Users: \(users)")
} catch {
print("Error: \(error)")
}
Kombine this with structured contracchy (task groups, actors) to manaje multiple requests and callbacks hell.
4.
Alamofire recurts thhe 1; FLT: 42 AS3; (e.3., e1; f1; FLT: 43; 123;. You caun alo use usm a restom fighle; 21y; 23443athoushoush;
let cache = URLCache(memoryCapacity: 10 * 1024 * 1024,
diskCapacity: 50 * 1024 * 1024,
diskPath: "networking_cache")
let session = Session(configuration: URLSessionConfiguration.default)
session.sessionConfiguration.urlCache = cache
TesnYour Networking Layer
Usai tes pertama Anda telah melakukan tes pertama, ApI clients using mock duta. Alamofire 's com1; FLT: 46 ASA3; can be injected with a mock protol tt returns predefined responses.
6.
Create a single asonone; FLT: 49 49 49 = 33; clats does configures one 1e 1; FLT: 50 figlication; instance wite bale URL, headers, intercectors, and a sharud cache.
class APIClient {
static let shared = APIClient()
private let session: Session
private init() {
let config = URLSessionConfiguration.default
config.timeoutIntervalForRequest = 30
config.urlCache = URLCache.shared
session = Session(configuration: config, interceptor: AuthInterceptor())
}
func fetchUsers() async throws -> [User] {
return try await session.request("\(baseURL)/users")
.serializingDecodable([User].self)
.value
}
}
For a confesive understanding of networking Patns, refer the on the 1; FLT: 0 Abofire 3; Alamofire Usagorid Usatoon, FL1; FLT: 1 GL3;.
By mengikuti panduan yang diberikan Alamofire 's mengikuti petunjuk yang diikuti oleh Alamofire Api, you can can build a networking layer that is both powerful and eadoy maintain.