AFNetworking的使用

1.下载AFNetworking资源包 https://github.com/AFNetworking/AFNetworking

2.将资源包添加到工程文件。

3.在工程的Supporting File群组中打开预编译头文件XXX-Prefix.pch。然后在别的import后面添加如下一行代码#import “AFNetworking”

将AFNetworking添加到预编译头文件,意味着这个框架会被自动的添加到工程的所有源代码文件中。

4.AFNetworking通过网络来加载和处理结构化的数据非常明智,它支持JSON,XML,Property List。

 

[plain] view plaincopyprint?

  1. static NSString*const BaseURLString = @"http://www.raywenderlich.com/downloads/weather_sample/";

  2.  

  3. // 1

  4. NSString *weatherUrl = [NSStringstringWithFormat:@"%@weather.php?format=json",BaseURLString];

  5. NSURL *url = [NSURLURLWithString:weatherUrl];

  6. NSURLRequest *request = [NSURLRequestrequestWithURL:url];

  7.  

  8. // 2

  9. AFJSONRequestOperation *operation =

  10. [AFJSONRequestOperationJSONRequestOperationWithRequest:request

  11. success:^(NSURLRequest*request, NSHTTPURLResponse *response, id JSON) {

  12. //

  13. NSDictionary*dicWeather = (NSDictionary *)JSON;

  14. NSLog(@"result:%@",dicWeather);

  15. }

  16. failure:^(NSURLRequest*request, NSHTTPURLResponse *response, NSError *error, id JSON) {

  17. UIAlertView*alertView = [[UIAlertView alloc] initWithTitle:@"Error RetrievingWeather"

  18. message:[NSStringstringWithFormat:@"%@",error]

  19. delegate:self

  20. cancelButtonTitle:@"OK"

  21. otherButtonTitles: nil];

  22. [alertView show];

  23. }];

  24. // 5

  25. [operation start];

static NSString*const BaseURLString = @"http://www.raywenderlich.com/downloads/weather_sample/";
   
    // 1
    NSString *weatherUrl = [NSStringstringWithFormat:@"%@weather.php?format=json",BaseURLString];
    NSURL *url = [NSURLURLWithString:weatherUrl];
    NSURLRequest *request = [NSURLRequestrequestWithURL:url];
   
    // 2
    AFJSONRequestOperation *operation =
    [AFJSONRequestOperationJSONRequestOperationWithRequest:request
                                              success:^(NSURLRequest*request, NSHTTPURLResponse *response, id JSON) {
                                                 //
                                                 NSDictionary*dicWeather = (NSDictionary *)JSON;
                                                 NSLog(@"result:%@",dicWeather);
                                              }
                                              failure:^(NSURLRequest*request, NSHTTPURLResponse *response, NSError *error, id JSON) {
                                                 UIAlertView*alertView = [[UIAlertView alloc] initWithTitle:@"Error RetrievingWeather"
                                                                                               message:[NSStringstringWithFormat:@"%@",error]
                                                                                              delegate:self
                                                                                      cancelButtonTitle:@"OK"
                                                                                      otherButtonTitles: nil];
                                                 [alertView show];
                                              }];
    // 5
    [operation start];

 

(1)根据基本的URL构造除完整的一个URL,然后通过这个完整的URL获得一个NSURL对象,然后根据这个url获得一个NSURLRequest。

(2)AFJSONRequestOperation是一个完整的类,整合了从网络中获取数据并对JSON进行解析。

(3)当请求成功,则运行成功块。在本例中,把解析出来的天气数据从JSON变量转换为一个字典(dictionary),并将其存储在字典中。

(4)如果运行出问题了,则运行失败块(failure block),比如网络不可用。如果failure block被调用了,将会通过提示框显示错误信息。

 

6.AFNetWorking异步加载图片

 

[plain] view plaincopyprint?

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

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

  3. __weak UIImageView *_imageView = imageView;

  4. [imageViewsetImageWithURLRequest:[[NSURLRequest alloc] initWithURL:[NSURLURLWithString:@"http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0001_sunny.png"]]

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

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

  7. _imageView.image = image;

  8.  

  9. [_imageView setNeedsDisplay];

  10. }

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

  12. ;

  13. }];

  14. [self.view addSubview:imageView];

(1)#import “UIImageView+AFNetworking.h”
(2)UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(40, 80, 40, 40)];
    __weak UIImageView *_imageView = imageView;
    [imageViewsetImageWithURLRequest:[[NSURLRequest alloc] initWithURL:[NSURLURLWithString:@"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];

 

7.GET 和POST请求

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

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

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

(4).POST请求跟GET一样

 

[plain] view plaincopyprint?

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

  2. [clientregisterHTTPOperationClass:[AFJSONRequestOperation class]];

  3. [clientsetDefaultHeader:@"Accept" value:@"application/json"];

  4. [client postPath:@"weather.php"

  5. parameters:parameters

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

  7. self.weather =responseObject;

  8. self.title = @"HTTPPOST";

  9. [self.tableViewreloadData];

  10. }

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

  12. UIAlertView *av =[[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather"

  13. message:[NSStringstringWithFormat:@"%@",error]

  14. delegate:nil

  15. cancelButtonTitle:@"OK" otherButtonTitles:nil];

  16. [av show];

  17.  

  18. }

  19. ];

  20.  

  21. [client getPath:@"weather.php"

  22. parameters:parameters

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

  24. self.weather =responseObject;

  25. self.title = @"HTTP GET";

  26. [self.tableViewreloadData];

  27. }

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

  29. UIAlertView *av =[[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather"

  30. message:[NSStringstringWithFormat:@"%@",error]

  31. delegate:nil

  32. cancelButtonTitle:@"OK" otherButtonTitles:nil];

  33. [av show];

  34.  

  35. }

  36. ];

AFHTTPClient *client= [[AFHTTPClient alloc] initWithBaseURL:baseURL];
[clientregisterHTTPOperationClass:[AFJSONRequestOperation class]];
[clientsetDefaultHeader:@"Accept" value:@"application/json"];
[client postPath:@"weather.php"
              parameters:parameters
                success:^(AFHTTPRequestOperation *operation, id responseObject) {
                     self.weather =responseObject;
                     self.title = @"HTTPPOST";
                     [self.tableViewreloadData];
                 }
                failure:^(AFHTTPRequestOperation *operation, NSError*error) {
                     UIAlertView *av =[[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather"
                                                                 message:[NSStringstringWithFormat:@"%@",error]
                                                                delegate:nil
                                                       cancelButtonTitle:@"OK" otherButtonTitles:nil];
                     [av show];
 
                 }
         ];
 
[client getPath:@"weather.php"
             parameters:parameters
               success:^(AFHTTPRequestOperation *operation, id responseObject) {
                    self.weather =responseObject;
                    self.title = @"HTTP GET";
                    [self.tableViewreloadData];
                }
               failure:^(AFHTTPRequestOperation *operation, NSError*error) {
                    UIAlertView *av =[[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather"
                                                                 message:[NSStringstringWithFormat:@"%@",error]
                                                               delegate:nil
                                                      cancelButtonTitle:@"OK" otherButtonTitles:nil];
                    [av show];
 
                }
         ];

 

8.AFNetworking更新背景图片

Note:

AFJSONOperation,AFPropertyListOperation, AFXMLOperation用来解析结构化数据。

UIImageView+AFNetworking用来快捷的填充image view

AFHTTPClient用来进行更底层的请求

用自定义的AFHTTPClient子类来访问一个web service。

AFNetworkActivityIndicatiorManager用来给用户做出网络访问的提示。

AFImageRequestOperation用来加载图片。

 

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