AFNetworking:OC,✩33.1k
Alamofire:Swift,✩35.3k
1. AFNetworking
cd到工程目录:
cd /Users/kang/Desktop/AFNetworking_Demo_OC
创建 Podfile 文件:
touch Podfile
使用vim编辑文件(或者直接双击文件打开编辑):
vim Podfile
键入i,进入输入模式,输入内容:
platform :ios, '10.0'
target 'AFNetworking_Demo_OC' do
pod 'AFNetworking'
end
按Esc退出输入模式,然后:wq保存并退出。
接着执行update操作,等待下载第三方库:
pod update
于是乎:
AFNetworking
如需开启HTTP,需在info.plist添加如下配置:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
下面开始撸代码。
1.1 Data Task
- (void)dataTask {
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:@"http://httpbin.org/get"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request
uploadProgress:nil
downloadProgress:nil
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
NSLog(@"Error: %@", error);
} else {
NSLog(@"response: %@", responseObject);
NSLog(@"responseObject: %@", responseObject);
}
}];
[dataTask resume];
}
1.2 Upload Task
- (void)uploadTask {
// 要上传的数据
NSData *uploadData = [@"test123" dataUsingEncoding:NSUTF8StringEncoding];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:@"http://httpbin.org/post"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
request.HTTPMethod = @"POST";
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request
fromData:uploadData
progress:nil
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
NSLog(@"Error: %@", error);
} else {
NSLog(@"response: %@", responseObject);
NSLog(@"responseObject: %@", responseObject);
}
}];
[uploadTask resume];
}
1.3 Upload Task for a Multi-Part Request
- (void)uploadTaskMulti {
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST"
URLString:@"http://httpbin.org/post"
parameters:nil
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
// 要上传的数据
// NSData *uploadData1 = [@"data1" dataUsingEncoding:NSUTF8StringEncoding];
// NSData *uploadData2 = [@"data2" dataUsingEncoding:NSUTF8StringEncoding];
// [formData appendPartWithFileData:uploadData1 name:@"data1" fileName:@"data1" mimeType:@"text/plain"];
// [formData appendPartWithFileData:uploadData2 name:@"data2" fileName:@"data2" mimeType:@"text/plain"];
// 要上传的数据
NSString *imagePath1 = [[NSBundle mainBundle] pathForResource:@"image1" ofType:@"png"];
NSString *imagePath2 = [[NSBundle mainBundle] pathForResource:@"image2" ofType:@"png"];
[formData appendPartWithFileURL:[NSURL fileURLWithPath:imagePath1] name:@"file" fileName:@"image1.png" mimeType:@"image/png" error:nil];
[formData appendPartWithFileURL:[NSURL fileURLWithPath:imagePath2] name:@"file" fileName:@"image2.png" mimeType:@"image/png" error:nil];
} error:nil];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionUploadTask *uploadTask;
uploadTask = [manager uploadTaskWithStreamedRequest:request
progress:^(NSProgress * _Nonnull uploadProgress) {
NSLog(@"progress: %f", uploadProgress.fractionCompleted);
}completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
NSLog(@"Error: %@", error);
} else {
NSLog(@"response: %@", responseObject);
NSLog(@"responseObject: %@", responseObject);
}
}];
[uploadTask resume];
}
1.4 Download Task
- (void)downloadTask {
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:@"http://httpbin.org/image/jpeg"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
NSLog(@"progress: %@", downloadProgress);
} destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
// 下载文件保存路径
NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
} completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
NSLog(@"File downloaded to: %@", filePath);
}];
[downloadTask resume];
}
1.5 Request Serialization
NSString *URLString = @"http://example.com";
NSDictionary *parameters = @{@"foo": @"bar", @"baz": @[@1, @2, @3]};
1. AFHTTPRequestSerializer GET
[[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:URLString parameters:parameters error:nil];
/*
GET http://example.com?foo=bar&baz[]=1&baz[]=2&baz[]=3
*/
2. AFHTTPRequestSerializer POST
[[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters error:nil];
/*
POST http://example.com/
Content-Type: application/x-www-form-urlencoded
foo=bar&baz[]=1&baz[]=2&baz[]=3
*/
3. AFJSONRequestSerializer
[[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters error:nil];
/*
POST http://example.com/
Content-Type: application/json
{"foo": "bar", "baz": [1,2,3]}
*/
2. Alamofire
2.1 简单请求
GET
AF.request("https://httpbin.org/get").responseData { (response) in
debugPrint(response)
}
POST
let parameters = ["name": "kang"]
AF.request("https://httpbin.org/post", method: .post, parameters: parameters, encoder: URLEncodedFormParameterEncoder.default).validate(statusCode: 200..<300).validate(contentType: ["application/json"]).responseJSON { (response) in
debugPrint(response)
}
2.2 下载
func download() {
// 目的地址
let destination: DownloadRequest.Destination = { _, _ in
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let fileURL = documentsURL.appendingPathComponent("image.png")
return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
}
// 下载
AF.download("https://httpbin.org/image/png", to: destination)
.downloadProgress { progress in
print("Download Progress: \(progress.fractionCompleted)")
}
.response { response in
debugPrint(response)
if response.error == nil, let imagePath = response.fileURL?.path {
let image = UIImage(contentsOfFile: imagePath)
}
}
}
2.3 上传
func upload() {
struct HTTPBinResponse: Decodable { let url: String }
// Uploading Data
let data = Data("data123".utf8)
AF.upload(data, to: "https://httpbin.org/post").responseDecodable(of: HTTPBinResponse.self) { response in
debugPrint(response)
}
// Uploading a File
guard let fileURL = Bundle.main.url(forResource: "image", withExtension: "png") else { return }
AF.upload(fileURL, to: "https://httpbin.org/post").responseDecodable(of: HTTPBinResponse.self) { response in
debugPrint(response)
}
// Uploading Multipart Form Data
AF.upload(multipartFormData: { multipartFormData in
multipartFormData.append(Data("one".utf8), withName: "one")
multipartFormData.append(Data("two".utf8), withName: "two")
}, to: "https://httpbin.org/post")
.uploadProgress { progress in
print("Upload Progress: \(progress.fractionCompleted)")
}
.responseDecodable(of: HTTPBinResponse.self) { response in
debugPrint(response)
}
}
网友评论