SwiftyNetworking
特性
- 直接目标模型对象解码
- 以模型形式传递参数
- 以 MultipartFormData 形式上传 jpg/png 图片
- 实例直接缓存下载图片
- 以数据下载请求方式下载文件
- HTTP 响应验证
- 网络可达性
- 无单例限制
- 后台任务
要求
- iOS 11+
- Xcode 10.1+
- Swift 4.2+
安装
CocoaPods
SwiftyNetworking可通过CocoaPods使用。要安装它,只需将以下行添加到您的Podfile中:
pod 'SwiftyNetworking'
HTTP请求示例
要运行示例项目,请克隆存储库,然后首先从示例目录运行pod install
。####数据请求 - 返回模型对象
// Targeted model object
struct UserModel: Codable {
let userId: Float
let id: Float
let title: String
let completed: Bool
}
// Error targeted model object
struct CommonErrorModel: Codable {
let message: String
let error: Error
}
// Request
let url = URL(string: "https://jsonplaceholder.typicode.com/todos/1")
let headers: [String: Any] = ["Authorization": "76GTLYj8j2"]
// headers are optional
SwiftyNetworking.requestModelResponse(URL: url!, Headers: headers, HTTPMethod: .get) { (result: ModelResult<UserModel,CommonErrorModel>, statusCode) in
switch result {
case .success(let user):
print(user.title)
case .catchError(let errorModel):
print(errorModel)
case .failure(let error):
print(error.localizedDescription)
}
}
####数据请求 - 带参数 - 返回模型对象
// Parameters model
struct UserRequiredInfoModel: Codable{
let Id: Int
let status: Bool
init(ID: Int, Status: Bool){
self.Id = ID
self.status = Status
}
}
// Request
let url = URL(string: "https://jsonplaceholder.typicode.com/todos/1")
let parameters = UserRequiredInfoModel(ID: 112239, Status: false)
let headers: [String: Any] = ["Authorization": "76GTLYj8j2"]
// headers are optional
SwiftyNetworking.requestModelResponse(URL: url!, Parameters: parameters, Headers: headers, HTTPMethod: .get) { (result: ModelResult<UserModel,CommonErrorModel>, statusCode) in
switch result {
case .success(let user):
print(user.title)
case .catchError(let errorModel):
print(errorModel)
case .failure(let error):
print(error.localizedDescription)
}
}
####数据请求 - 返回JSON
let url = URL(string: "https://jsonplaceholder.typicode.com/todos/1")
let headers: [String: Any] = ["Authorization": "76GTLYj8j2"]
// headers are optional
SwiftyNetworking.requestJsonResponse(URL: url!, Headers: headers, HTTPMethod: .get) { (result, statusCode) in
switch result {
case .success(let jsonResponse):
print(jsonResponse)
case .failure(let error):
print(error.localizedDescription)
}
}
####数据请求 - 返回数据作为Data
SwiftyNetworking.requestDataResponse(URL: url!, Headers: nil, HTTPMethod: .get) { (result, statusCode) in
switch result {
case .success(let data):
// Do whatever you want
print(data)
return
case .failure(let error):
print(error)
}
}
下载图片示例
####带有缓存的下载图片 - 显示加载指示器
// loading indicator - Defualt color
imageView.downloadImage(urlString: "https://images.unsplash.com/photo-1515627909249-5a98b247c9f2?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1500&q=80", loadingIndicator: true) { (Error) in
if let error = Error {
print(error.localizedDescription)
}
}
// loading indicator - Custom color
imageView.downloadImage(urlString: "https://images.unsplash.com/photo-1515627909249-5a98b247c9f2?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1500&q=80", loadingIndicator: true, IndicatorColor: UIColor.red) { (Error) in
if let error = Error {
print(error.localizedDescription)
}
}
####下载图片 - 返回下载的图片
let tempImage = UIImageView()
tempImage.downloadImage(urlString: "https://images.unsplash.com/photo-1515627909249-5a98b247c9f2?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1500&q=80") { (downloadedImage, Error) in
if let error = Error {
print(error.localizedDescription)
return
}
// Do what you want with the downloaded image
}
####删除图片缓存
// Delete image cache
SwiftyNetworking.deleteImageCache(urlString: "https://images.unsplash.com/photo-1515627909249-5a98b247c9f2?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1500&q=80")
// Delete all cached images
SwiftyNetworking.deleteAllImageCache()
上传图片示例
####将图片作为multipart/form-data上传
let uploadURL = URL(string: "https://api.imgur.com/3/image")
let headers: [String: String] = [
"Authorization": "Client-ID 341be54e0da4496"
]
// headers are optional
let parameters: [String: Any] = [
"name": "Image1",
"description": "Photo Image"
]
let media = Media(withImage: UIImage(named: "PhoneICON")!, imageName: "ramy", forKey: "image", mimeType: .pngImage, withCompression: 1)
SwiftyNetworking.uploadImageWithJsonResponse(Images: [media!], URL: uploadURL!, Parameters: parameters, Headers: headers) { (result, statusCode) in
switch result {
case .success(let jsonResult):
print(jsonResult)
print(statusCode)
return
case .failure(let error):
print(error)
print(statusCode)
return
}
}
作者
ramysabry22,[yiyou@example.com]
许可证
SwiftyNetworking可在MIT许可证下使用。有关更多信息,请参阅LICENSE文件。