AFNetworking框架的使用

时间:2021-11-10 23:49:43

#import "ViewController.h"

#import "AFNetworking.h"



@interface ViewController ()



@end



@implementation ViewController



- (void)viewDidLoad {

    [super viewDidLoad];



}



-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{



   

    [self sendGet];

//    [self sendPost];

//    [self upLoad];

//    [self downLoad];

    

   

//    默认就是异步的请求!

}



/**

 *  get 请求

 */

- (void) sendGet{



    AFHTTPRequestOperationManager * mamaner=[AFHTTPRequestOperationManager manager];//单例

    

    //设置解析返回的数据的类型(默认就是解析json的)(能够设置,有三种)

//    mamaner.responseSerializer=[AFHTTPResponseSerializer serializer];//无论返回什么样的数据,统一解析成二进制数据

//    mamaner.responseSerializer = [AFXMLParserResponseSerializer serializer];//返回的是xml的,使用这个

//    mamaner.responseSerializer = [AFJSONResponseSerializer serializer];//默认的

    

    //get请求两种写法

    //(1)写法一

    NSString * url=@"http://192.168.2.162/logo.php?

userName=jereh&pwd=123";

    [mamaner GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

        

        NSLog(@"%@",responseObject);

        

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        NSLog(@"%@",error);

    }];

    

    //(2)写法二。类似post的写法

//    NSString * url=@"http://192.168.2.162/logo.php";

//    NSDictionary * dic=@{@"userName":@"jereh",@"pwd":@"123"};

//    [mamaner GET:url parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {

//        

//        NSLog(@"%@",responseObject);

//        

//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

//        NSLog(@"%@",error);

//    }];

    

}



/**

 *  post 请求

 */

- (void) sendPost{

    

    AFHTTPRequestOperationManager * mamaner=[AFHTTPRequestOperationManager manager];

    

    //    mamaner.responseSerializer=[AFHTTPResponseSerializer serializer];

    

    

    

    NSString * url=@"http://192.168.2.162/loginPost";

    NSDictionary * dic=@{@"userName":@"jereh",@"pwd":@"123"};

    

    [mamaner POST:url parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {

        

        NSLog(@"%@",responseObject);



        

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        NSLog(@"%@",error);

    }];

 

    

}









/**

 *  post 请求(上传,使用post)

 */

- (void) upLoad{



    AFHTTPRequestOperationManager * mamaner=[AFHTTPRequestOperationManager manager];



    mamaner.responseSerializer=[AFHTTPResponseSerializer serializer];

    

    NSString * url=@"http://192.168.2.162/upload.php";



    

    [mamaner POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {

        

        NSURL * url=[[NSBundle mainBundle] URLForResource:@"exclusive_title_icon.png" withExtension:nil];

        [formData appendPartWithFileURL:url name:@"file" fileName:@"jereh.png" mimeType:@"image/png" error:nil];

        

        

    } success:^(AFHTTPRequestOperation *operation, id responseObject) {

        

        NSString * str=[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];

        NSLog(@"%@",str);

        

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        NSLog(@"%@",error);

    }];

    

    

}









/**

 *  post 请求(下载,get请求)

 */

- (void) downLoad{

    

    //(0)创建manager对象

    NSURLSessionConfiguration * config=[NSURLSessionConfiguration defaultSessionConfiguration];

    AFURLSessionManager * manager=[[AFURLSessionManager alloc] initWithSessionConfiguration:config];

    

    

    //(1)监控下载进度

    [manager setDownloadTaskDidWriteDataBlock:^(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite) {

        //注意当前线程是子线程。须要返回主线程刷新数据

        CGFloat progress=totalBytesWritten*1.0/totalBytesExpectedToWrite;//写入的比上总共的

        dispatch_sync(dispatch_get_main_queue(), ^{

            self.progress.progress=progress;

        });

    }];

    

    //(2)请求

    NSURLRequest * request=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://192.168.2.162/test.rar"]];

    //注意下边的方法有返回值,block也有一个返回值

    NSURLSessionDownloadTask *task= [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {

        

        NSString * cache=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];

        cache =[cache stringByAppendingPathComponent:@"jereh.rar"];

        

        NSURL * url=[NSURL fileURLWithPath:cache];

        

        return url;

        

        

    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {

        

        if (error) {

            NSLog(@"下载失败了");

        }else{

            NSLog(@"下载完毕");

        }

        

    }];

    

    //(3)開始任务(注意要写这一句)

    [task resume];

    

}





@end