AFNetWorking的简单使用

来源:互联网 发布:大数据技术入门 pdf 编辑:程序博客网 时间:2024/05/22 03:27

首先,对于AFNetWorking,我们要知道它的框架结构,AFURLConnectionOperation继承于NSObject,AFHTTPRequestOperation继承于AFURLConnectionOperation,然后JSON,XML,plist,Image数据继承于AFHTTPRequestOperation。


,AFNetworking的使用

1. 将AFNetWorking文件夹导入项目

2. 添加类库 Security.framework、MobileCoreServices.framework、SystemConfiguration.framework

3. 在使用的地方 #import “AFNetworking.h"


  1. 根据基本的URL构造除完整的一个URL,然后通过这个完整的URL获得一个NSURL对象,然后根据这个url获得一个NSURLRequest。 
  2. AFJSONRequestOperation是一个完整的类,整合了从网络中获取数据并对JSON进行解析。 
  3. 当请求成功,则运行成功块。在本例中,把解析出来的天气数据从JSON变量转换为一个字典(dictionary),并将其存储在字典中。 
  4. 如果运行出问题了,则运行失败块(failure block),比如网络不可用。如果failure block被调用了,将会通过提示框显示错误信息。

例:

如何通过URL获取json数据


第一种,利用AFJSONRequestOperation

NSString *str=[NSStringstringWithFormat:@"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, idresponseObject) {

        NSString *html = operation.responseString;

             NSData* data=[html dataUsingEncoding:NSUTF8StringEncoding];

             iddict=[NSJSONSerialization  JSONObjectWithData:data options:0 error:nil];

        NSLog(@"获取到的数据为:%@",dict);

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

        NSLog(@"发生错误!%@",error);

    }];

    NSOperationQueue *queue = [[NSOperationQueue alloc] init];

    [queue addOperation:operation];


2,AFNetWorking异步加载图片

(1)#import “UIImageView+AFNetworking.h”  

(2)UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(40, 80, 40, 40)];      

 __weak UIImageView *_imageView = imageView;      

[imageView setImageWithURLRequest:[[NSURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0001_sunny.png"]]                     

placeholderImage:[UIImage imageNamed:@"placeholder.png"]              

success:^(NSURLRequest *request,NSHTTPURLResponse *response, UIImage *image) {                              

_imageView.image = image;    

[_imageView setNeedsDisplay];   }    

failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {                                ;                             }];    

[self.view addSubview:imageView];


如何通过URL获取图片


NSURLRequest *request = [NSURLRequestrequestWithURL:[NSURLURLWithString:@"http://www.scott-sherwood.com/wp-content/uploads/2013/01/scene.png"]];

    AFImageRequestOperation *operation = [AFImageRequestOperation imageRequestOperationWithRequest:request imageProcessingBlock:nil success:^(NSURLRequest*request, NSHTTPURLResponse *response, UIImage *image) {

        self.backgroundImageView.image = image;

    } failure:^(NSURLRequest*request, NSHTTPURLResponse *response, NSError *error) {

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

    }];

 

    [operation start];


如何通过URL获取plist文件


NSString *weatherUrl = @"http://www.calinks.com.cn/buick/kls/Buickhousekeeper.plist";

    NSURL *url = [NSURL URLWithString:[weatherUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    [AFPropertyListRequestOperation addAcceptableContentTypes:[NSSet setWithObject:@"text/plain"]];

    AFPropertyListRequestOperation *operation = [AFPropertyListRequestOperation propertyListRequestOperationWithRequest:request success:^(NSURLRequest*request, NSHTTPURLResponse *response, id propertyList) {

        NSLog(@"%@",(NSDictionary *)propertyList);

        

    }failure:^(NSURLRequest *request,NSHTTPURLResponse *response, NSError *error, id propertyList) {

        NSLog(@"%@",error);

    }];

 

    [operation start];


如何通过URL获取XML数据


xml解析使用AFXMLRequestOperation需要实现苹果自带的NSXMLParserDelegate委托方法,XML中有一些不需要的协议格式内容,所以就不能像json那样解析,还得实现委托。我之前有想过能否所有的XML链接用一个类处理,而且跟服务端做了沟通,结果很不方便,效果不好。XML大多标签不同,格式也不固定,所以就有问题,使用json就要方便的多。

第一步;在.h文件中加入委托NSXMLParserDelegate

第二步;在.m文件方法中加入代码

   NSURL *url = [NSURLURLWithString:@"http://113.106.90.22:5244/sshopinfo"];

    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    AFXMLRequestOperation *operation =

    [AFXMLRequestOperation XMLParserRequestOperationWithRequest:request success:^(NSURLRequest*request, NSHTTPURLResponse *response, NSXMLParser *XMLParser) {

        XMLParser.delegate = self;

        [XMLParser setShouldProcessNamespaces:YES];

        [XMLParser parse];

    }failure:^(NSURLRequest *request,NSHTTPURLResponse *response, NSError *error, NSXMLParser *XMLParser) {

        NSLog(@"%@",error);

    }];

    [operation start];

第三步;在.m文件中实现委托方法

    //在文档开始的时候触发

-(void)parserDidStartDocument:(NSXMLParser *)parser{

    NSLog(@"解析开始!");

}

//解析起始标记

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{

    NSLog(@"标记:%@",elementName);

    

}

//解析文本节点

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{

    NSLog(@"值:%@",string);

}

//解析结束标记

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{

    NSLog(@"结束标记:%@",elementName);

}

//文档结束时触发

-(void) parserDidEndDocument:(NSXMLParser *)parser{

    NSLog(@"解析结束!");

}


如何使用AFHTTPClient进行web service操作


AFHTTPClient处理GET POST请求.做网页的朋友们这个方法用的比较多。在要经常调用某个请求时,可以封装,节省资源。

   BaseURLString = @"http://www.raywenderlich.com/downloads/weather_sample/";

    NSURL *baseURL = [NSURL URLWithString:[NSString stringWithFormat:BaseURLString]];

    NSDictionary *parameters = [NSDictionary dictionaryWithObject:@"json" forKey:@"format"];

    AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:baseURL];

    

    [client registerHTTPOperationClass:[AFJSONRequestOperation class]];

    [client setDefaultHeader:@"Accept" value:@"text/html"];

    [client postPath:@"weather.php"parameters:parameters success:^(AFHTTPRequestOperation *operation,id responseObject) {

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

        NSLog(@"POST请求:%@",newStr);

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

        NSLog(@"%@",error);

    }];

    

    [client getPath:@"weather.php"parameters:parameters success:^(AFHTTPRequestOperation *operation,id responseObject) {

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

        NSLog(@"GET请求:%@",newStr);

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

        NSLog(@"%@",error);

    }];



3,GET 和POST请求 (其它PUT,PATCH等不多做介绍)

构建一个baseURL,以及一个参数字典,并将这两个变量传给AFHTTPClient. 

将AFJSONRequestOperation注册为HTTP的操作, 这样就可以跟之前的示例一样,可以获得解析好的JSON数据。 

做了一个GET请求,这个请求有一对block:success和failure。 

POST请求跟GET一样 

- (AFHTTPRequestOperation *)GET:(NSString *)URLString

                     parameters:(id)parameters

                        success:(void (^)(AFHTTPRequestOperation *operation,id responseObject))success

                        failure:(void (^)(AFHTTPRequestOperation *operation,NSError *error))failure


- (AFHTTPRequestOperation *)POST:(NSString *)URLString

                      parameters:(id)parameters

                         success:(void (^)(AFHTTPRequestOperation *operation,id responseObject))success

                         failure:(void (^)(AFHTTPRequestOperation *operation,NSError *error))failure;




4,多线程

在afnetworking里面,有一些封装的方法中使用到了多线程,这个不多说,大家自己看看比较好。


0 0
原创粉丝点击