由于之前看视频学习资料都用的是14年之前AFNetworking框架,和最新的有很大不同,为了方便大家使用,我列出了最基本的POST,GET请求方法。
GET:
[manager GET : @"http://example.com/resources.json" parameters : nil success :^( AFHTTPRequestOperation *operation, id responseObject) {
NSLog ( @"JSON: %@" , responseObject);
} failure :^( AFHTTPRequestOperation *operation, NSError *error) {
NSLog ( @"Error: %@" , error);
}];
POST :
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST : @"http://example.com/resources.json" parameters :parameters success :^( AFHTTPRequestOperation *operation, id responseObject) {
NSLog ( @"JSON: %@" , responseObject);
} failure :^( AFHTTPRequestOperation *operation, NSError *error) {
NSLog ( @"Error: %@" , error);
}];
POST(Multi-Part Request) :
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManagermanager];
NSDictionary *parameters = @{@"foo": @"bar"};
NSURL *filePath = [NSURLfileURLWithPath:@"file://path/to/image.png"];
[managerPOST:@"http://example.com/resources.json"parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formDataappendPartWithFileURL:filePath name:@"image" error:nil];
}success:^(AFHTTPRequestOperation *operation,id responseObject) {
NSLog(@"Success: %@", responseObject);
}failure:^(AFHTTPRequestOperation *operation,NSError *error) {
NSLog(@"Error: %@", error);
}];
创建下载任务(download):
NSURLSessionConfiguration *configuration = [NSURLSessionConfigurationdefaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManageralloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURLURLWithString:@"http://example.com/download.zip"];
NSURLRequest *request = [NSURLRequestrequestWithURL:URL];
NSURLSessionDownloadTask *downloadTask = [managerdownloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath,NSURLResponse *response) {
NSURL *documentsDirectoryURL = [[NSFileManagerdefaultManager] URLForDirectory:NSDocumentDirectoryinDomain:NSUserDomainMaskappropriateForURL:nilcreate:NOerror:nil];
return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
}completionHandler:^(NSURLResponse *response,NSURL *filePath, NSError *error) {
NSLog(@"File downloaded to: %@", filePath);
}];
[downloadTaskresume];
NSURLSessionConfiguration *configuration = [NSURLSessionConfigurationdefaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManageralloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURLURLWithString:@"http://example.com/upload"];
NSURLRequest *request = [NSURLRequestrequestWithURL:URL];
NSURL *filePath = [NSURLfileURLWithPath:@"file://path/to/image.png"];
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePathprogress:nilcompletionHandler:^(NSURLResponse *response,id responseObject, NSError *error) {
if (error) {
NSLog(@"Error: %@", error);
}else {
NSLog(@"Success: %@ %@", response, responseObject);
}
}];
[uploadTaskresume];