iOS开发之AFNetworking开源库的使用

iOS开发之AFNetworking开源库的使用

1.简介

  常见的处理网络请求方式

  (1)NSURLConnection/NSURLSession

  (2)ASIHttpRequest 早期项目中比较常见, 由于作者不更新了

  (3)AFNetworking 推荐使用, 项目中使用

  (4)MKNetworkKit 试试

2.配置和使用

  2.1 配置 

    库文件拖入工程中, 包含头文件 

    #import "AFNetworking.h"

  2.2 使用

 //演示AFNetworking的使用
    //1. GET请求(html,json,xml)
    //[self testGetRequset];
    
    //2.POST请求
    //[self testPostRequest];
    
    //3.上传文件(上传图片)
    //[self testUploadFile];
    
    //4.下载文件
    //[self testDownloadFile];
    
    //5.监控网络状态
    [self testMonitorNetworkStatus];
    
    //6.图片异步功能(替代SDWebImage)
    // UIKit+AFNetworking.h
    // - (void)setImageWithURL:(NSURL *)url;
    
    //7.有些请求特殊的请求头
    // BAIDU_WISE_UID=wapp_1428385381699_466;
    //AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    //[manager.requestSerializer setValue:@"wapp_1428385381699_466" forHTTPHeaderField:@"BAIDU_WISE_UID"];
    
}
-(void)testMonitorNetworkStatus
{
    AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:@"www.baidu.com"]];
    [manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        NSDictionary *dict =@{
    @(AFNetworkReachabilityStatusUnknown):@"未知",
    @(AFNetworkReachabilityStatusNotReachable):@"不可达",
    @(AFNetworkReachabilityStatusReachableViaWWAN):@"GPRS",
    @(AFNetworkReachabilityStatusReachableViaWiFi):@"Wifi",};
        
        NSLog(@"状态为 %@",dict[@(status)]);
        
    }];
    //开启状态监视
    [manager.reachabilityManager startMonitoring];
    
}



-(void)testDownloadFile
{
    NSString *urlString = @"http://imgcache.qq.com/club/item/avatar/zip/7/i87/all.zip";
    
    //创建会话管理器对象(通过默认配置)
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    
    NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]] progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        
        //返回文件保存位置
        NSString *path = [NSString stringWithFormat:@"%@/Documents/all.zip",NSHomeDirectory()];
        NSLog(@"path = %@",path);
        return [NSURL fileURLWithPath:path];
        
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        NSLog(@"下载完成");
    }];
    //启动任务
    [task resume];
    
    
}
-(void)testUploadFile
{
    //POST上传接口
    NSString *urlString = @"http://quiet.local/uploadtest/upload.php";
    //参数名: image : 参数值是图片
    AFHTTPRequestOperationManager *mamager = [AFHTTPRequestOperationManager manager];
    mamager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [mamager POST:urlString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        
        //实现: 上传的数据附加到请求体中
        //mimeType 多用途互联网邮件扩展类型, 每种文件都有一个类型
        NSString *path = [[NSBundle mainBundle] pathForResource:@"IMG_4131.JPG" ofType:nil];
        NSLog(@"path = %@",path);
        [formData appendPartWithFileURL:[NSURL fileURLWithPath:path] name:@"image" fileName:@"quiet1.jpg" mimeType:@"image/jpeg" error:nil];
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSLog(@"str = %@",str);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"error = %@",error);
    }];
    
}
-(void)testPostRequest
{
    //POST接口:http://quiet.local/testdir/login.php
    //参数1: @"user" : @"quiet"
    //参数2: @"password" : @"123"
    NSString *urlString = @"http://quiet.local/testdir/login.php";
    
    AFHTTPRequestOperationManager *mamager = [AFHTTPRequestOperationManager manager];
    mamager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    //参数1: 传入地址
    //参数2: 传入URL请求的参数, 格式传入字典
    [mamager POST:urlString parameters:@{@"user":@"quiet",@"password":@"123"} success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSLog(@"str = %@",str);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"error = %@",error);
    }];
    
    
}
-(void)testGetRequset
{
    NSString *urlString = @"http://www.baidu.com";
    urlString = @"http://m.weather.com.cn/data/101010100.html";
    
    //定义AFNetworking管理
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    //注意: 默认认为数据是JSON,content-type也是JSON, responseObject是解析的字典和数组, 不是产生错误Code=-1016
    //解决: 设置解析器为HTTP形式, 下载回来是NSData
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:urlString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        //responseObject重要参数,包含下载数据
        //NSLog(@"o = %@",responseObject);
        NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSLog(@"str = %@",str);
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"error = %@",error);
    }];
}

 

  

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。