AF的请求 是基于NSURLReuqest的。且使用的时异步队列,AFHTTPRequestOperation
转载地址,感谢原作者
在新版的AFNetWorking加入了监听当前网络的状态,可以判断当前的移动设备是出于3G/WIFI/还是2G等...,但是新版的需要导入官方库。
使用新版的AFNetWorking需添加官方库:(旧版的不需要)
Security.framework
MobileCoreService.framework
SystemConfiguration.framework
在AFNetWork中设置最大等待时间,可以通过创建请求的时候设置。
//创建请求并设置超时时间
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[baseUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
AFNetWork可以有多种请求方式,包含了8种HTTP请求的方式。
!!需要 最后设置开始请求的方式有: [operation start];
在旧版中:
AFHTTPRequestOperation 默认的普通请求,它返回的是NSData数据,需要json或xml解析。
AFJSONRequestOperation json请求,它返回的是json解析后的结果(数组或者字典)。
AFXMLRequestOperation ……
不需要设置开始请求,它会自动开始请求的是:
AFHTTPClient --- 它可以设置(8种Http请求方式)
- -(void)startReuest
- {
-
-
-
- NSURL *url=[NSURL URLWithString:@"https://api.douban.com/v2/book/search?q=harry&start=0"];
- AFHTTPRequestOperation *operation=[[AFHTTPRequestOperation alloc] initWithRequest:[NSURLRequest requestWithURL:url]];
-
- [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
-
-
-
-
- } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
-
- }];
-
-
- [operation start];
- }
-
- -(void)jsonReuqest
- {
- NSURL *url=[NSURL URLWithString:@"https://api.douban.com/v2/book/search?q=harry&start=0"];
-
-
- AFJSONRequestOperation *operation=[[AFJSONRequestOperation alloc] initWithRequest:[NSURLRequest requestWithURL:url]];
-
- [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
-
- } failure:
- ^(AFHTTPRequestOperation *operation, NSError *error) {
-
- }];
-
- [operation start];
- }
-
- -(void)clientRequest
- {
-
- AFHTTPClient *client=[[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://10.0.8.8/sns/"]];
-
-
-
-
- [client getPath:@"my/user_list.php" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
-
-
-
- } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
-
- }];
-
- [client postPath:@"my/user_list.php" parameters:@{@"count":@"20"} success:^(AFHTTPRequestOperation *operation, id responseObject) {
-
-
-
- } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
-
- }];
-
- }
在新版中:
新版的 AFNetWorking请求是基于一个请求队列管理器 AFHTTPRequestOperationManager来实现请求的。
使用新版的AFNetWorking需添加官方库:(旧版的不需要)
Security.framework
MobileCoreService.framework
SystemConfiguration.framework
代码:
- #pragma mark - 判断当前网络状态
- - (void)monitorNetworkType
- {
-
-
-
- AFHTTPRequestOperationManager * manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:@"www.baidu.com"]];
-
-
- [manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
-
-
-
- switch (status) {
- case AFNetworkReachabilityStatusNotReachable:
- NSLog(@"网络未连接");
- break;
- case AFNetworkReachabilityStatusReachableViaWWAN:
- NSLog(@"3G网络");
- break;
- case AFNetworkReachabilityStatusReachableViaWiFi:
- NSLog(@"WIFI网络");
- break;
-
-
- default:
- break;
- }
-
- }];
-
-
- [manager.reachabilityManager startMonitoring];
- }
-
- #pragma mark - 异步加载图片
-
- - (void)asyncLoadImage
- {
-
- UIImageView * imageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
- [self.view addSubview:imageView];
-
- [imageView setImageWithURL:[NSURL URLWithString:@"http://10.0.8.8/sns/my/headimage.php?uid=10"]];
- }
-
- #pragma mark - GET请求 JSON数据
-
- - (void)jsonGetRequest
- {
-
- NSString * urlString = @"http://10.0.8.8/sns/my/user_list.php";
-
-
- AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
-
-
-
- manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", nil nil];
-
-
-
- [manager GET:urlString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
-
-
- NSLog(@"%@", responseObject);
-
- } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
-
- NSLog(@"%@", error);
- }];
- }
-
-
- #pragma mark - GET请求 非JSON数据
- - (void)dataGetRequest
- {
- NSString * urlString = @"http://10.0.8.8/sns/my/user_list.php";
-
- AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
-
-
- manager.responseSerializer = [AFHTTPResponseSerializer serializer];
-
- [manager GET:urlString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
-
-
- NSString * str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
-
- NSLog(@"%@", str);
-
- } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
- NSLog(@"%@", error);
- }];
- }
-
- #pragma mark - POST请求
- - (void)postRequest
- {
- NSString * url = @"http://localhost/cgi-bin/post1.cgi";
-
-
-
- AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
-
-
- manager.responseSerializer = [AFHTTPResponseSerializer serializer];
-
-
- NSDictionary * dict = @{@"username":@"Tom", @"password":@"123456", @"message":@"woooooooooow"};
-
-
- [manager POST:url parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
-
- NSLog(@"成功!%@",[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
-
- } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
-
- NSLog(@"失败%@", error);
-
- }];
-
- }
-
- #pragma mark - 上传文件
- - (void)uploadFile
- {
- NSString * url = @"http://localhost/cgi-bin/post2.cgi";
-
- AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
-
-
- manager.responseSerializer = [AFHTTPResponseSerializer serializer];
-
-
-
- [manager POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
-
-
-
- NSString * imagePath = [[NSBundle mainBundle] pathForResource:@"annotation" ofType:@"png"];
-
-
- NSData * data = [NSData dataWithContentsOfFile:imagePath];
-
-
- [formData appendPartWithFileData:data name:@"image" fileName:@"annotation.png" mimeType:@"image/png"];
-
-
-
- } success:^(AFHTTPRequestOperation *operation, id responseObject) {
-
- NSLog(@"成功");
-
- } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
-
- NSLog(@"失败");
-
- }];
- }
-
- #pragma mark - 文件下载
- - (void)requestFile
- {
- NSString * urlString = @"http://10.0.8.8/download/归档Archieve.pdf";
-
- AFURLSessionManager * manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
-
-
-
- urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
-
- NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
-
-
-
-
- __autoreleasing NSProgress * progress = nil;
-
-
-
- NSURLSessionDownloadTask * task = [manager downloadTaskWithRequest:request progress:&progress destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
-
- NSString * path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/视频.mp4"];
- return [NSURL fileURLWithPath:path];
-
- } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
-
- if (error) {
- NSLog(@"%@", error);
- }
- }];
-
-
- [task resume];
-
- _task = task;
-
- NSLog(@"%@", NSHomeDirectory());
-
-
- _progress = progress;
-
-
-
- [_progress addObserver:self forKeyPath:@"fractionCompleted" options:NSKeyValueObservingOptionNew context:nil];
- }
-
-
- - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(voidvoid *)context
- {
- if (object == _progress && [keyPath isEqualToString:@"fractionCompleted"] == YES) {
-
- NSLog(@"%.2f%%", _progress.fractionCompleted * 100);
- }
- }