AFNetWorking的基本使用

如何通过URL获取json数据
第一种,利用AFJSONRequestOperation,官方网站上给的例子:
    NSString *str=[NSString stringWithFormat:@"https://alpha-api.app.net/stream/0/posts/stream/global"];
    NSURL *url = [NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    //    从URL获取json数据
    AFJSONRequestOperation *operation1 = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, NSDictionary* JSON) {
                NSLog(@"获取到的数据为:%@",JSON);
    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id data) {
        NSLog(@"发生错误!%@",error);
    }];
[operation1 start];



第二种方法,利用AFHTTPRequestOperation 先获取到字符串形式的数据,然后转换成json格式,将NSString格式的数据转换成json数据,利用IOS5自带的json解析方法:
   NSString *str=[NSString stringWithFormat:@"https://alpha-api.app.net/stream/0/posts/stream/global"];
    NSURL *url = [NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
   AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *html = operation.responseString;
             NSData* data=[html dataUsingEncoding:NSUTF8StringEncoding];
             id dict=[NSJSONSerialization  JSONObjectWithData:data options:0 error:nil];
        NSLog(@"获取到的数据为:%@",dict);
    }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"发生错误!%@",error);
    }];
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    [queue addOperation:operation];


如果发生Error Domain=NSURLErrorDomain Code=-1000 "bad URL" UserInfo=0x14defc80 {NSUnderlyingError=0x14deea10 "bad URL", NSLocalizedDescription=bad URL这个错误,请检查URL编码格式。有没有进行stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding
关于其他的各种类型的数据请求就不多说了,大家有兴趣的话可以去这个博客里看看: http://blog.sina.com.cn/s/blog_68661bd80101r1xz.html

基于AFDownloadRequestOperation的断点续传
整体测试代码如下:
#import "RootViewController.h"
#import "AFDownloadRequestOperation.h"
#define MUSICFile [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/test2.mp4"]//设置文件路径
static BOOL a=YES;//控制暂停和下载
@interface RootViewController ()
{
    AFDownloadRequestOperation *operation;
}
@property (strong, nonatomic) IBOutlet UILabel *currtenLabel;//显示当前文件的下载的大小
@property (strong, nonatomic) IBOutlet UILabel *totalLabel;//显示整体的文件的大小
@property (strong, nonatomic) IBOutlet UILabel *progressLabel;//显示下载的百分比

@property (strong, nonatomic) IBOutlet UIProgressView *progressView;//下载的进度条

@end

@implementation RootViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.currtenLabel.text = @"CUR : 0 M";
    self.totalLabel.text = @"TOTAL : 0 M";

}
- (IBAction)start:(id)sender {
    if (a==YES) {
        
    
    
    NSString * urlStr=@"http://vf1.mtime.cn/Video/2012/04/23/mp4/120423212602431929.mp4";
    
    NSURL *url = [NSURL URLWithString:urlStr];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:3600];
    
     operation = [[AFDownloadRequestOperation alloc] initWithRequest:request targetPath:MUSICFile shouldResume:YES];
    
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"下载成功");
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"下载失败");
    }];
    
    __block RootViewController * this=self;
    [operation setProgressiveDownloadProgressBlock:^(NSInteger bytesRead, long long totalBytesRead, long long totalBytesExpected, long long totalBytesReadForFile, long long totalBytesExpectedToReadForFile) {
        float percentDone = totalBytesReadForFile/(float)totalBytesExpectedToReadForFile;
        
        this.progressView.progress = percentDone;
        this.progressLabel.text = [NSString stringWithFormat:@"%.0f%%",percentDone*100];
        
        this.currtenLabel.text = [NSString stringWithFormat:@"CUR : %lli M",totalBytesReadForFile/1024/1024];
        this.totalLabel.text = [NSString stringWithFormat:@"TOTAL : %lli M",totalBytesExpectedToReadForFile/1024/1024];
        
        NSLog(@"------%f",percentDone);
        NSLog(@"Operation%i: bytesRead: %d", 1, bytesRead);
        NSLog(@"Operation%i: totalBytesRead: %lld", 1, totalBytesRead);
        NSLog(@"Operation%i: totalBytesExpected: %lld", 1, totalBytesExpected);
        NSLog(@"Operation%i: totalBytesReadForFile: %lld", 1, totalBytesReadForFile);
        NSLog(@"Operation%i: totalBytesExpectedToReadForFile: %lld", 1, totalBytesExpectedToReadForFile);
    }];
    [operation start];
    
    NSLog(@"%@",MUSICFile);
    }
    else{
    
    [operation pause];
    }
    a=!a;

}

//注意:1.如果你的文件已经下载完成过,请更换文件的路径,否则会出现不能断点续传的现象;
2.请保证你的下载路径的文件的格式与你保存的路径的文件格式一致;
例如 上面的  #define MUSICFile [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/test2.mp4"]//设置文件路径
NSString * urlStr=@"http://vf1.mtime.cn/Video/2012/04/23/mp4/120423212602431929.mp4";
两者的最后的文件格式都是.mp4


基于AFHTTPClient的POST请求
代码如下:    NSDictionary *parameters = @{@"key": @"value",
                                 @"name": @"pig"};
    
    AFHTTPClient *client= [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://www.xxxxx.com"]];
    [client setParameterEncoding:AFJSONParameterEncoding];
    [client postPath:@"xxxxx.php"
          parameters:parameters
             success:^(AFHTTPRequestOperation *operation, id responseObject) {
                 NSLog(@"%@",operation.responseString);
                 NSLog(@"%@",operation.request.URL);
                 
                 NSLog(@"提交成功");
             }
             failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                 NSLog(@"%@",operation.request.URL);
                 NSLog(@"提交失败");
                 
             }
     ];
    
xxxx代表你要填入的地址,个人把xxxx替换成baidu,结果你成功的.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值