iOS AFNetworking 各种功能封装类代码攻略
什么是 AFNetworking?
AFNetworking 是一个 iOS & macOS 平台上的网络请求框架,它是由 Objective-C 编写而成,是一个轻量级的网络库,提供了 URLSession API 不具备的高级别的抽象。AFNetworking 已经被 iOS 开发者广泛应用于网络请求方面,它提供了方便易用的 API 接口和多种功能封装。
在 iOS 开发中,我们通常需要通过网络请求实现客户端与服务器端的数据交换,而 AFNetworking 通过提供了常用的 GET/POST 请求、文件上传、图片下载、JSON解析等多种功能的封装,大大简化了这方面的开发。下面将为大家讲解,如何使用 AFNetworking 实现常见的几种网络请求功能。
安装 AFNetworking
- Cocoapods 安装
在项目的 Podfile
文件中添加如下依赖代码:
ruby
pod 'AFNetworking', '~> 4.0'
然后在项目根目录下运行 pod install
命令进行安装。
- 手动集成
下载 AFNetworking 最新版的源代码集成到项目中。
Get 请求
常规请求
- Objective-C 代码示例
objective-c
// 初始化AFHTTPSessionManager对象
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
// 请求API接口数据
[manager GET:@"https://api.apiopen.top/getJoke?page=1&count=1&type=video" parameters:nil headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"responseObject: %@", responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"error: %@", error);
}];
- Swift 代码示例
swift
// 初始化AFHTTPSessionManager对象
let manager = AFHTTPSessionManager()
// 请求API接口数据
manager.get("https://api.apiopen.top/getJoke?page=1&count=1&type=video", parameters: nil, headers: nil, progress: nil, success: { (task, responseObject) in
print("responseObject: \(String(describing: responseObject))")
}) { (task, error) in
print("error: \(error.localizedDescription)")
}
带参数请求
- Objective-C 代码示例
objective-c
// 参数
NSDictionary *parameters = @{@"page": @"1",
@"count": @"10",
@"type": @"text"
};
// 初始化AFHTTPSessionManager对象
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
// 请求API接口数据
[manager GET:@"https://api.apiopen.top/getJoke" parameters:parameters headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"responseObject: %@", responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"error: %@", error);
}];
- Swift 代码示例
swift
// 参数
let parameters: [String: Any] = ["page": "1",
"count": "10",
"type": "text"
]
// 初始化AFHTTPSessionManager对象
let manager = AFHTTPSessionManager()
// 请求API接口数据
manager.get("https://api.apiopen.top/getJoke", parameters: parameters, headers: nil, progress: nil, success: { (task, responseObject) in
print("responseObject: \(String(describing: responseObject))")
}) { (task, error) in
print("error: \(error.localizedDescription)")
}
POST 请求
普通参数请求
- Objective-C 代码示例
objective-c
// 参数
NSDictionary *parameters = @{@"username": @"jack",
@"password": @"123456"
};
// 初始化AFHTTPSessionManager对象
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
// 请求API接口数据
[manager POST:@"https://api.apiopen.top/login" parameters:parameters headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"responseObject: %@", responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"error: %@", error);
}];
- Swift 代码示例
swift
// 参数
let parameters: [String: Any] = ["username": "jack",
"password": "123456"
]
// 初始化AFHTTPSessionManager对象
let manager = AFHTTPSessionManager()
// 请求API接口数据
manager.post("https://api.apiopen.top/login", parameters: parameters, headers: nil, progress: nil, success: { (task, responseObject) in
print("responseObject: \(String(describing: responseObject))")
}) { (task, error) in
print("error: \(error.localizedDescription)")
}
JSON 参数请求
有些接口需要我们传递给服务器的参数不是以普通的参数形式(如:@{ @"username":@"jack", @"password":@"123456" }),而是 JSON 格式的字符串。此时我们需要在 headers 中添加 “Content-Type” 字段。
- Objective-C 代码示例
objective-c
// 参数
NSDictionary *parameters = @{@"username": @"jack",
@"password": @"123456"
};
// 初始化AFHTTPSessionManager对象
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
// 设置请求头
manager.requestSerializer = [AFJSONRequestSerializer serializer];
// 请求API接口数据
[manager POST:@"https://api.apiopen.top/login" parameters:parameters headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"responseObject: %@", responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"error: %@", error);
}];
- Swift 代码示例
swift
// 参数
let parameters: [String: Any] = ["username": "jack",
"password": "123456"
]
// 初始化AFHTTPSessionManager对象
let manager = AFHTTPSessionManager()
// 设置请求头
manager.requestSerializer = AFJSONRequestSerializer()
// 请求API接口数据
manager.post("https://api.apiopen.top/login", parameters: parameters, headers: nil, progress: nil, success: { (task, responseObject) in
print("responseObject: \(String(describing: responseObject))")
}) { (task, error) in
print("error: \(error.localizedDescription)")
}
文件上传
普通请求上传
- Objective-C 代码示例
objective-c
// 上传文件
NSURL *url = [[NSBundle mainBundle] URLForResource:@"test.jpg" withExtension:nil];
NSData *data = [NSData dataWithContentsOfURL:url];
// 参数
NSDictionary *parameters = @{@"username": @"jack",
@"password": @"123456"
};
// 初始化AFHTTPSessionManager对象
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
// 请求API接口数据
[manager POST:@"https://api.apiopen.top/update" parameters:parameters headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
[formData appendPartWithFileData:data name:@"file" fileName:@"test.jpg" mimeType:@"image/jpeg"];
} progress:^(NSProgress * _Nonnull uploadProgress) {
CGFloat progress = uploadProgress.fractionCompleted;
NSLog(@"上传进度: %f", progress);
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"responseObject: %@", responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"error: %@", error);
}];
- Swift 代码示例
swift
// 上传文件
let url = Bundle.main.url(forResource: "test", withExtension: "jpg")!
let data = try! Data(contentsOf: url)
// 参数
let parameters: [String: Any] = ["username": "jack",
"password": "123456"
]
// 初始化AFHTTPSessionManager对象
let manager = AFHTTPSessionManager()
// 请求API接口数据
manager.post("https://api.apiopen.top/update", parameters: parameters, headers: nil, constructingBodyWith: { (formData: AFMultipartFormData) in
formData.appendPart(withFileData: data, name: "file", fileName: "test.jpg", mimeType: "image/jpeg")
}, progress: { (uploadProgress: Progress) in
let progress = uploadProgress.fractionCompleted
print("上传进度: \(progress)")
}, success: { (task, responseObject) in
print("responseObject: \(String(describing: responseObject))")
}) { (task, error) in
print("error: \(error.localizedDescription)")
}
断点续传上传
- Objective-C 代码示例
objective-c
// 上传文件
NSURL *url = [[NSBundle mainBundle] URLForResource:@"test.jpg" withExtension:nil];
NSData *data = [NSData dataWithContentsOfURL:url];
// 参数
NSDictionary *parameters = @{@"username": @"jack",
@"password": @"123456"
};
// 初始化AFURLSessionManager对象
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
// 创建断点续传的请求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://api.apiopen.top/update"]];
request.HTTPMethod = @"POST";
NSURLSessionUploadTask *uploadTask;
// 判断该文件是否需要断点续传
if ([self checkResumeData]) {
NSData *resumeData = [self getResumeData];
uploadTask = [manager uploadTaskWithResumeData:resumeData fromFile:url progress:^(NSProgress * _Nonnull uploadProgress) {
CGFloat progress = uploadProgress.fractionCompleted;
NSLog(@"上传进度: %f", progress);
} completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
NSLog(@"error: %@", error);
} else {
NSLog(@"responseObject: %@", responseObject);
}
}];
} else {
uploadTask = [manager uploadTaskWithRequest:request fromFile:url progress:^(NSProgress * _Nonnull uploadProgress) {
CGFloat progress = uploadProgress.fractionCompleted;
NSLog(@"上传进度: %f", progress);
} completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
NSLog(@"error: %@", error);
} else {
NSLog(@"responseObject: %@", responseObject);
}
}];
}
// 开始上传
[uploadTask resume];
- Swift 代码示例
swift
// 上传文件
let url = Bundle.main.url(forResource: "test", withExtension: "jpg")!
let data = try! Data(contentsOf: url)
// 参数
let parameters: [String: Any] = ["username": "jack",
"password": "123456"
]
// 初始化AFURLSessionManager对象
let manager = AFURLSessionManager(sessionConfiguration: .default)
// 创建断点续传的请求
var request = URLRequest(url: URL(string: "https://api.apiopen.top/update")!)
request.httpMethod = "POST"
var uploadTask: URLSessionUploadTask
// 判断该文件是否需要断点续传
if self.checkResumeData() {
let resumeData = self.getResumeData()
do {
let resumeDict = try JSONSerialization.jsonObject(with: resumeData, options: []) as? [String: Any]
uploadTask = try manager.uploadTask(withResumeData: resumeData, from: url, progress: { (uploadProgress: Progress) in
let progress = uploadProgress.fractionCompleted
print("上传进度: \(progress)")
}, completionHandler: { (response: URLResponse, responseObject: Any?, error: Error?) in
if error != nil {
print("error: \(error.debugDescription)")
} else {
print("responseObject: \(String(describing: responseObject))")
}
}) as URLSessionUploadTask
} catch {
print(error.localizedDescription)
return
}
} else {
uploadTask = try! manager.uploadTask(with: request, fromFile: url)
uploadTask.taskDescription = "file"
uploadTask.resume()
}
// 开始上传
uploadTask.resume()
图片下载
- Objective-C 代码示例
objective-c
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(20, 100, 200, 200)];
[self.view addSubview:imageView];
// 初始化AFHTTPSessionManager对象
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
// 请求API接口数据
[manager GET:@"https://th.bing.com/th/id/OIP.p9I9Z8xdbYJ30Bzti9PMqAHaEK?w=274&h=180&c=7&o=5&pid=1.7" parameters:nil headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSData *data = [NSData dataWithData:responseObject];
UIImage *image = [UIImage imageWithData:data];
imageView.image = image;
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"error: %@", error);
}];
- Swift 代码示例
swift
let imageView = UIImageView(frame: CGRect(x: 20, y: 100, width: 200, height: 200))
view.addSubview(imageView)
// 初始化AFHTTPSessionManager对象
let manager = AFHTTPSessionManager()
// 请求API接口数据
manager.get("https://th.bing.com/th/id/OIP.p9I9Z8xdbYJ30Bzti9PMqAHaEK?w=274&h=180&c=7&o=5&pid=1.7", parameters: nil, headers: nil, progress: nil, success: { (task, responseObject) in
let data = responseObject as! Data
let image = UIImage(data: data)!
imageView.image = image
}) { (task, error) in
print("error: \(error.localizedDescription)")
}
总结
本文章详细讲解了如何使用 AFNetworking 实现常见的 GET/POST 请求、文件上传、图片下载等功能。对于初学者而言,可以通过此教程入门 AFNetworking,对于有经验的开发者而言,可以巩固自己的知识储备。
以上便是本文的全部内容,由于 AFNetworking 拥有多元化的功能封装,笔者并没有涵盖其全部功能。如果有其他 AFNetworking 的使用技巧、优化方案等方面的问题,可以通过评论区和笔者进行交流。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:iOS AFNetworking各种功能封装类代码 - Python技术站