AFNetworking框架的使用


#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];
    
   
//    默認就是異步的請求!

php


}

/**
 *  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?json

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

session

相關文章
相關標籤/搜索