AFNetworking的使用之广不必多说了,下面直接上代码.。
首先是准备工作,导入AFNetworking以及Masonry(Masonry是因为个人喜欢用而已,不喜欢用的可以不用导入).
1、AppDelegate中
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
HomeViewController *VC=[[HomeViewController alloc] init];
UINavigationController *navi=[[UINavigationController alloc] initWithRootViewController:VC];
self.window.rootViewController=navi;
return YES;
}
2、HomeViewController
// HomeViewController.m
// AFNetworking使用
//
// Created by 鲁杜杨 on 15/10/2.
// Copyright © 2015年 鲁杜杨. All rights reserved.
//
#import "HomeViewController.h"
#import "Masonry.h"
@interface HomeViewController ()
@property(nonatomic,retain) NSArray *ViewControllers;
@end
@implementation HomeViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[self uiConfig];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark - Private Method
-(void)uiConfig
{
self.view.backgroundColor=[UIColor whiteColor];
self.title=@"AFNetworking";
NSArray *titleArr=@[@"GET",@"POST",@"Download",@"Upload",@"Parameter Encoding",@"NetWork Reachability"];
for (int i=0; i<[titleArr count]; i++) {
UIButton *kBtn=[UIButton buttonWithType:UIButtonTypeCustom];
[kBtn setBackgroundColor:[UIColor cyanColor]];
[kBtn setTitle:titleArr[i] forState:UIControlStateNormal];
[kBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
[kBtn setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
kBtn.tag=10+i;
[kBtn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:kBtn];
CGFloat topOffSet=150+i*(40+20);
[kBtn mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(self.view.mas_top).offset(topOffSet);
make.height.mas_equalTo(40);
make.centerX.equalTo(self.view.mas_centerX);
}];
[kBtn setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];
[kBtn setContentCompressionResistancePriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];
}
}
-(void)btnAction:(UIButton *)mBtn
{
NSInteger num=mBtn.tag-10;
Class className=NSClassFromString(self.ViewControllers[num]);
UIViewController *VC=[[className alloc] init];
VC.title=self.ViewControllers[num];
[self.navigationController pushViewController:VC animated:YES];
}
-(NSArray *)ViewControllers
{
if (_ViewControllers==nil) {
_ViewControllers=@[@"GetViewController",@"PostViewController"
,@"DownloadViewController",@"UploadViewController"
,@"ParameEncodetersViewController",@"ReachabilityViewController"];
}
return _ViewControllers;
}
@end
下面的视图控制器均继承于BaseViewController ,只是#import “AFNetworking.h”,讨厌一次次的导入。前期的准备工作到此结束,下面开始使用。
3、GET请求 (GetViewController)
// GetViewController.m
// AFNetworking使用
// Created by 鲁杜杨 on 15/10/2.
// Copyright © 2015年 鲁杜杨. All rights reserved.
#import "GetViewController.h"
@interface GetViewController ()
@end
@implementation GetViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[self method1];
[self method2];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
-(void)method1
{
AFHTTPRequestOperationManager *manager=[AFHTTPRequestOperationManager manager];
// // 返回的数据格式是XML
// manager.responseSerializer=[AFXMLParserResponseSerializer serializer];
//默认返回数据类型为json类型
//数据请求在子线程中,回调函数在主线程中,所以可以直接刷新UI
[manager GET:@"http://iappfree.candou.com:8080/free/applications/limited?currency=rmb&page=1" parameters:nil success:^(AFHTTPRequestOperation * _Nonnull operation, id _Nonnull responseObject) {
NSLog(@"json=%@",responseObject);
} failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
NSLog(@"Error:%@",error);
}];
}
//AFHTTPRequestOperation` is a subclass of `AFURLConnectionOperation` for requests using the HTTP or HTTPS protocols. It encapsulates the concept of acceptable status codes and content types, which determine the success or failure of a request.
//Although `AFHTTPRequestOperationManager` is usually the best way to go about making requests, `AFHTTPRequestOperation` can be used by itself.
-(void)method2
{
NSURL *URL=[NSURL URLWithString:@"http://example.com/resources/123.json"];
NSURLRequest *request=[NSURLRequest requestWithURL:URL];
AFHTTPRequestOperation *op=[[AFHTTPRequestOperation alloc] initWithRequest:request];
op.responseSerializer=[AFJSONResponseSerializer serializer];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation * _Nonnull operation, id _Nonnull responseObject) {
NSLog(@"JSON:%@",responseObject);
} failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
NSLog(@"Error:%@",error);
}];
[[NSOperationQueue mainQueue] addOperation:op];
}
@end
4、POST请求(PostViewController)
// PostViewController.m
// AFNetworking使用
// Created by 鲁杜杨 on 15/10/2.
// Copyright © 2015年 鲁杜杨. All rights reserved.
#import "PostViewController.h"
@interface PostViewController ()
@end
@implementation PostViewController
- (void)viewDidLoad
{
[super viewDidLoad];
//数据请求是在子线程中进行的,回调函数是在主线程中,所以可以直接刷新UI。
[self method1];
[self method2];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
//URL-Form-Encoded Request
-(void)method1
{
AFHTTPRequestOperationManager *manager=[AFHTTPRequestOperationManager manager];
//默认请求格式、返回格式均为JSON
// //设置请求格式
// manager.requestSerializer=[AFJSONRequestSerializer serializer];
// //设置返回格式
// manager.responseSerializer=[AFJSONResponseSerializer serializer];
NSDictionary *parameters=@{@"foo":@"bar"};
[manager POST:@"http://example.com/resources.json" parameters:parameters success:^(AFHTTPRequestOperation * _Nonnull operation, id _Nonnull responseObject) {
NSLog(@"JSON:%@",responseObject);
} failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
NSLog(@"Error:%@",error);
}];
}
//Multi-Part Request
-(void)method2
{
AFHTTPRequestOperationManager *manager=[AFHTTPRequestOperationManager manager];
NSDictionary *parameters=@{@"foo":@"bar"};
NSString *path=[[NSBundle mainBundle] pathForResource:@"image.png" ofType:@"image/jepg"];
NSURL *filePath=[NSURL fileURLWithPath:path];
[manager POST:@"http://example.com/resources.json" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
[formData appendPartWithFileURL:filePath name:@"image" error:nil];
} success:^(AFHTTPRequestOperation * _Nonnull operation, id _Nonnull responseObject) {
NSLog(@"success:%@",responseObject);
} failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
NSLog(@"Error:%@",error);
}];
}
//Batch of Operations
-(void)method3
{
NSMutableArray *mutableOperations=[[NSMutableArray alloc] init];
NSArray *fileToUpload;
for (NSURL *fileURL in fileToUpload) {
NSURLRequest *request=[[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
[formData appendPartWithFileURL:fileURL name:@"images[]" error:nil];
} error:nil];
AFHTTPRequestOperation *operation=[[AFHTTPRequestOperation alloc] initWithRequest:request];
[mutableOperations addObject:operation];
}
NSArray *operations=[AFURLConnectionOperation batchOfRequestOperations:mutableOperations progressBlock:^(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations) {
NSLog(@"%lu of %lu complete",numberOfFinishedOperations,totalNumberOfOperations);
} completionBlock:^(NSArray * _Nonnull operations) {
NSLog(@"All operations completed");
}];
[[NSOperationQueue mainQueue] addOperations:operations waitUntilFinished:YES];
}
@end
4、下载 (DownloadViewController)
//
// DownloadViewController.m
// AFNetworking
//
// Created by 鲁杜杨 on 15/10/2.
// Copyright © 2015年 鲁杜杨. All rights reserved.
//
#import "DownloadViewController.h"
@interface DownloadViewController ()
@end
@implementation DownloadViewController
- (void)viewDidLoad
{
[super viewDidLoad];
//数据请求是在子线程中进行的,回调函数是在主线程中,所以可以直接刷新UI。
[self method1];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
-(void)method1
{
NSURLSessionConfiguration *configuration=[NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager=[[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL=[NSURL URLWithString:@"http://example.com/download.zip"];
NSURLRequest *request=[NSURLRequest requestWithURL:URL];
NSURLSessionDownloadTask *downloadTask=[manager downloadTaskWithRequest:request progress:nil destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
// //指定下载文件保存的路径、将下载文件保存在混存路径中
// NSString *cacheDir=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
// NSString *path=[cacheDir stringByAppendingString:response.suggestedFilename];
// //URLWithString返回的是网络的URL。fileURLWithPath:返回的是本地的URL。
// NSURL *fileURL=[NSURL fileURLWithPath:path];
// return fileURL;
//或者
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];
}
@end
5、上传 (UploadViewController)
//
// UploadViewController.m
// AFNetworking
//
// Created by 鲁杜杨 on 15/10/2.
// Copyright © 2015年 鲁杜杨. All rights reserved.
//
#import "UploadViewController.h"
@interface UploadViewController ()
@end
@implementation UploadViewController
- (void)viewDidLoad
{
[super viewDidLoad];
//数据请求是在子线程中进行的,回调函数是在主线程中,所以可以直接刷新UI。
[self method1];
[self method2];
[self method3];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
//随机生成文件名
-(void)method1
{
NSURLSessionConfiguration *configuration=[NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager=[[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL=[NSURL URLWithString:@"http://example.com/upload"];
NSURLRequest *request=[NSURLRequest requestWithURL:URL];
NSURL *filePath=[NSURL fileURLWithPath:@"file://path/to/pig.png"];
NSURLSessionUploadTask *uploadTask=[manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
NSLog(@"Error:%@",error);
}else{
NSLog(@"Success:%@ %@",response,responseObject);
}
}];
[uploadTask resume];
}
//Creating an Upload Task for a Multi-Part Request, with Progress
//指定文件名
-(void)method2
{
NSMutableURLRequest *request=[[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
NSURL *fileURL=[[NSBundle mainBundle] URLForResource:@"pig.png" withExtension:nil];
[formData appendPartWithFileURL:fileURL name:@"fileName" fileName:@"fileName.pn" mimeType:@"image/png" error:nil];
} error:nil];
AFURLSessionManager *manager=[[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSProgress *progress=nil;
NSURLSessionUploadTask *uploadTask=[manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
NSLog(@"Error:%@",error);
}else{
NSLog(@"%@ %@",response,responseObject);
}
}];
[uploadTask resume];
}
//Creating a Data Task
-(void)method3
{
NSURLSessionConfiguration *configuration=[NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager=[[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL=[NSURL URLWithString:@"http://example.com/upload"];
NSURLRequest *request=[NSURLRequest requestWithURL:URL];
NSURLSessionDataTask *dataTask=[manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
NSLog(@"Error:%@",error);
}else{
NSLog(@"%@ %@",response,responseObject);
}
}];
[dataTask resume];
}
@end
6、请求参数编码说明 (ParameEncodetersViewController)
// ParameEncodetersViewController.m
// AFNetworking
// Created by 鲁杜杨 on 15/10/3.
// Copyright © 2015年 鲁杜杨. All rights reserved.
#import "ParameEncodetersViewController.h"
@interface ParameEncodetersViewController ()
@end
#define URLSTRING @"http://example.com"
#define PARAMETERS @{@"foo": @"bar", @"baz": @[@1, @2, @3]}
@implementation ParameEncodetersViewController
- (void)viewDidLoad
{
[super viewDidLoad];
//Query String Parameter Encoding
[[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:URLSTRING parameters:PARAMETERS error:nil];
//GET http://example.com?foo=bar&baz[]=1&baz[]=2&baz[]=3
//URL Form Parameter Encoding
[[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
//JSON Parameter Encoding
[[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLSTRING parameters:PARAMETERS error:nil];
//POST http://example.com/
//Content-Type: application/json
//{"foo": "bar", "baz": [1,2,3]}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
@end
7、网络连接 (ReachabilityViewController)
// ReachabilityViewController.m
// AFNetworking使用
// Created by 鲁杜杨 on 15/10/2.
// Copyright © 2015年 鲁杜杨. All rights reserved.
#import "ReachabilityViewController.h"
@interface ReachabilityViewController ()
@end
@implementation ReachabilityViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[self method1];
[self method2];
[self method3];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
//判断当前网络是否可用
-(void)method1
{
AFNetworkReachabilityManager *manager=[AFNetworkReachabilityManager sharedManager];
BOOL reachability=manager.reachable;
if (reachability) {
NSLog(@"网络可用");
}else{
NSLog(@"网络不可用");
}
}
//Shared Network Reachability
-(void)method2
{
[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
NSLog(@"Reachability:%@",AFStringFromNetworkReachabilityStatus(status));
}];
[[AFNetworkReachabilityManager sharedManager] startMonitoring];
}
//HTTP Manager Reachability
-(void)method3
{
NSURL *baseURL=[NSURL URLWithString:@"http://example.com/"];
AFHTTPRequestOperationManager *manager=[[AFHTTPRequestOperationManager alloc] initWithBaseURL:baseURL];
NSOperationQueue *operationQueue=manager.operationQueue;
[manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
switch (status) {
case AFNetworkReachabilityStatusReachableViaWWAN:
case AFNetworkReachabilityStatusReachableViaWiFi:
[operationQueue setSuspended:NO];
case AFNetworkReachabilityStatusNotReachable:
default:
[operationQueue setSuspended:YES];
break;
}
}];
[manager.reachabilityManager startMonitoring];
}
@end
AFNetworking 新版本3.0中,废弃了NSURLConnection的API(之前使用的AFURLConnectionOperation、AFHTTPRequestOperation、AFHTTPRequestOperationManager不再可以使用),修改了UIImageView+AFNetworking、UIWebView+AFNetworking、UIButton+AFNetworking,下面是3.0以及以后的使用
AppDelegate.h
#import "AppDelegate.h"
#import "ViewController.h"
@interface AppDelegate ()
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch./Users/luduyang/Desktop/
CGRect rect=[UIScreen mainScreen].bounds;
self.window=[[UIWindow alloc] initWithFrame:rect];
ViewController *VC=[[ViewController alloc] init];
UINavigationController *navi=[[UINavigationController alloc] initWithRootViewController:VC];
self.window.rootViewController=navi;
[self.window makeKeyAndVisible];
[[UINavigationBar appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor blueColor],NSFontAttributeName:[UIFont boldSystemFontOfSize:16]}];
[[UINavigationBar appearance] setBarTintColor:[UIColor orangeColor]];
[[UINavigationBar appearance] setTintColor:[UIColor blueColor]];
return YES;
}
BaseViewController
#import <UIKit/UIKit.h>
#import "AFNetworking.h"
@interface BaseViewController : UIViewController
@end
#import "BaseViewController.h"
@interface BaseViewController ()
@end
@implementation BaseViewController
- (void)viewDidLoad {
[super viewDidLoad];
// self.edgesForExtendedLayout=UIRectEdgeNone;
self.view.backgroundColor=[UIColor whiteColor];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
@end
ViewController.h
#import "ViewController.h"
#import "TableViewDataSource.h"
@interface ViewController () <UITableViewDelegate>
@property(nonatomic,retain) UITableView *kTableView;
@property(nonatomic,retain) TableViewDataSource *kDataSource;
@property(nonatomic,retain) NSArray *kDemoArr;
@end
@implementation ViewController
#pragma mark - Life Cycle
- (void)viewDidLoad {
[super viewDidLoad];
[self uiConfig];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
#pragma mark - UITableViewDelegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
Class className=NSClassFromString([NSString stringWithFormat:@"%@ViewController",self.kDemoArr[indexPath.row]]);
UIViewController *VC=[[className alloc] init];
VC.title=self.kDemoArr[indexPath.row];
[self.navigationController pushViewController:VC animated:YES];
}
#pragma mark - Private Method
-(void)uiConfig{
self.title=@"AFNetworking";
UIBarButtonItem *backItem=[[UIBarButtonItem alloc] initWithTitle:@"back" style:UIBarButtonItemStylePlain target:nil action:nil];
self.navigationItem.backBarButtonItem=backItem;
self.kDataSource=[[TableViewDataSource alloc] initWithItems:self.kDemoArr dataSourceType:TableViewDataSourceTypeArray configureCellBlock:^UITableViewCell *(id item) {
return [self configureCellWithDataOfIndexPath:item];
}];
self.kTableView.dataSource=self.kDataSource;
[self.view addSubview:self.kTableView];
}
-(UITableViewCell *)configureCellWithDataOfIndexPath:(id)item{
static NSString *cellId=@"cellId";
UITableViewCell *cell=[self.kTableView dequeueReusableCellWithIdentifier:cellId];
if (cell==nil) {
cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
cell.selectionStyle=UITableViewCellSelectionStyleNone;
cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
}
cell.textLabel.text=item;
return cell;
}
#pragma mark - Lazy Method
-(UITableView *)kTableView{
if (!_kTableView) {
_kTableView=[[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
_kTableView.delegate=self;
}
return _kTableView;
}
-(NSArray *)kDemoArr{
if (_kDemoArr==nil) {
_kDemoArr=@[@"Get",@"Download",@"Upload",@"UploadMultiPart",@"DataTask",
@"RequestSerialization",@"Reachability",@"Security"];
}
return _kDemoArr;
}
@end
GetViewController.h
#import "GetViewController.h"
@interface GetViewController ()
@end
@implementation GetViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self getRequest];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
-(void)getRequest{
NSURL *URL=[NSURL URLWithString:@"urlString"];
AFHTTPSessionManager *manager=[AFHTTPSessionManager manager];
[manager GET:URL.absoluteString parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"responseObject=%@",responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"error=%@",error.localizedDescription);
}];
}
@end
#import “SecurityViewController.h”
#import "SecurityViewController.h"
@interface SecurityViewController ()
@end
@implementation SecurityViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
//
//#import <SystemConfiguration/SystemConfiguration.h>
//#import <MobileCoreServices/MobileCoreServices.h>
//#define AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES
@end
ReachabilityViewController.h
#import "ReachabilityViewController.h"
#import "AFNetworkReachabilityManager.h"
@interface ReachabilityViewController ()
@end
@implementation ReachabilityViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self startMonitorsTheNetworkReaachability];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
-(void)startMonitorsTheNetworkReaachability{
[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
if (status==AFNetworkReachabilityStatusNotReachable) {
NSLog(@"网络不可用");
}else if (status==AFNetworkReachabilityStatusUnknown){
NSLog(@"未知");
}else if (status==AFNetworkReachabilityStatusReachableViaWWAN){
NSLog(@"万维网");
}else{
NSLog(@"无线网络");
}
}];
}
@end
RequestSerializationViewController.h
#import "RequestSerializationViewController.h"
@interface RequestSerializationViewController ()
@end
@implementation RequestSerializationViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
//Request serializers create requests from URL strings, encoding parameters as either a query string or HTTP body.
//
//```objective-c
//NSString *URLString = @"http://example.com";
//NSDictionary *parameters = @{@"foo": @"bar", @"baz": @[@1, @2, @3]};
//```
//
//#### Query String Parameter Encoding
//
//```objective-c
//[[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:URLString parameters:parameters error:nil];
//```
//
//GET http://example.com?foo=bar&baz[]=1&baz[]=2&baz[]=3
//
//#### URL Form Parameter Encoding
//
//```objective-c
//[[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
//
//#### JSON Parameter Encoding
//
//```objective-c
//[[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters error:nil];
//```
//
//POST http://example.com/
//Content-Type: application/json
//
//{"foo": "bar", "baz": [1,2,3]}
@end
DownloadViewController.h
#import "DownloadViewController.h"
@interface DownloadViewController ()
@end
@implementation DownloadViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self createADownloadTask];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
-(void)createADownloadTask{
NSURLSessionConfiguration *configuration=[NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager=[[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:@"http://example.com/download.zip"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
//或者
// return [self createDirectorywithDirectoryName:@"Download" andFileName:@"download.zip"];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
NSLog(@"File downloaded to: %@", filePath);
}];
[downloadTask resume];
}
-(NSURL *)createDirectorywithDirectoryName:(NSString *)directName andFileName:(NSString *)fileName{
NSString *documentPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *directPath=[documentPath stringByAppendingPathComponent:directName];
NSFileManager *fm=[NSFileManager defaultManager];
BOOL isdirect=YES;
if (![fm fileExistsAtPath:directPath isDirectory:&isdirect]) {
[fm createDirectoryAtPath:directPath withIntermediateDirectories:YES attributes:nil error:nil];
}
NSString *filePath=[directPath stringByAppendingPathComponent:fileName];
return [NSURL URLWithString:filePath];
}
@end
UploadViewController.h
#import "UploadViewController.h"
@interface UploadViewController ()
@end
@implementation UploadViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self createAnUploadTask];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
-(void)createAnUploadTask{
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSString *path=[[NSBundle mainBundle] pathForResource:@"1" ofType:@"jpg"];
NSURL *filePath=[NSURL URLWithString:path];
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
NSLog(@"Error: %@", error);
} else {
NSLog(@"Success: %@ %@", response, responseObject);
}
}];
[uploadTask resume];
}
@end
UploadMultiPartViewController.h
#import "UploadMultiPartViewController.h"
@interface UploadMultiPartViewController ()
@end
@implementation UploadMultiPartViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self createAnUploadTaskForMultiPartRequest];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
-(void)createAnUploadTaskForMultiPartRequest{
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
NSString *path=[[NSBundle mainBundle] pathForResource:@"1" ofType:@"jpg"];
[formData appendPartWithFileURL:[NSURL fileURLWithPath:path] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil];
} error:nil];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionUploadTask *uploadTask;
uploadTask = [manager
uploadTaskWithStreamedRequest:request
progress:^(NSProgress * _Nonnull uploadProgress) {
// This is not called back on the main queue.
// You are responsible for dispatching to the main queue for UI updates
dispatch_async(dispatch_get_main_queue(), ^{
//Update the progress view
// [progressView setProgress:uploadProgress.fractionCompleted];
NSLog(@"progress=%f",uploadProgress.fractionCompleted);
});
}
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
NSLog(@"Error: %@", error);
} else {
NSLog(@"%@ %@", response, responseObject);
}
}];
[uploadTask resume];
}
@end
DataTaskViewController.h
#import "DataTaskViewController.h"
@interface DataTaskViewController ()
@end
@implementation DataTaskViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self createADataTask];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
-(void)createADataTask{
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 completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
NSLog(@"Error: %@", error);
} else {
NSLog(@"%@ %@", response, responseObject);
}
}];
[dataTask resume];
}
@end