Created
August 6, 2014 15:19
-
-
Save YK-Unit/f683c49af14f3878dd86 to your computer and use it in GitHub Desktop.
AFNetworking 2.0 sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <Foundation/Foundation.h> | |
#import "AFNetworking.h" | |
@interface HTTPEngine : AFHTTPRequestOperationManager | |
+ (HTTPEngine *)sharedInstance; | |
- (AFHTTPRequestOperation *)getWeatherDataWithXMLFormat; | |
- (AFHTTPRequestOperation *)getWeatherDataWithJSONFormat; | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import "HTTPEngine.h" | |
#define BASEURL @"http://www.raywenderlich.com/" | |
@implementation HTTPEngine | |
+ (HTTPEngine *)sharedInstance | |
{ | |
static dispatch_once_t pred = 0; | |
__strong static HTTPEngine *_sharedHttp = nil; | |
dispatch_once(&pred, ^{ | |
_sharedHttp = [[self alloc] initWithBaseURL:[NSURL URLWithString:BASEURL]]; | |
}); | |
return _sharedHttp; | |
} | |
#pragma mark - API | |
- (AFHTTPRequestOperation *)getWeatherDataWithXMLFormat | |
{ | |
AFHTTPRequestOperation *requestOperation = [self GET:@"demos/weather_sample/weather.php" parameters:@{@"format":@"xml"} success:^(AFHTTPRequestOperation *operation, id responseObject) { | |
NSString *responseStr = [[NSString alloc] initWithData:operation.responseData encoding:NSUTF8StringEncoding]; | |
NSLog(@"XML:%@",responseStr); | |
NSLog(@"responseObject:%@",responseObject); | |
//接下来可使用XMLReader解析得到的 xml 数据 | |
/* | |
NSError *xmlPaserError = nil; | |
NSDictionary *responseDict = [XMLReader dictionaryForXMLData:operation.responseData error:&xmlPaserError]; | |
NSLog(@"responseDict:%@",responseDict); | |
*/ | |
} failure:^(AFHTTPRequestOperation *operation, NSError *error) { | |
NSLog(@"error:%@",error); | |
}]; | |
requestOperation.responseSerializer = [AFXMLParserResponseSerializer serializer]; | |
return requestOperation; | |
} | |
- (AFHTTPRequestOperation *)getWeatherDataWithJSONFormat | |
{ | |
AFHTTPRequestOperation *requestOperation = [self GET:@"demos/weather_sample/weather.php" parameters:@{@"format":@"json"} success:^(AFHTTPRequestOperation *operation, id responseObject) { | |
//此时得到的就是一个字典对象(NSDictionary),因为 AFNetworking 原生对 JSON 友好 | |
NSLog(@"JSON:%@",responseObject); | |
} failure:^(AFHTTPRequestOperation *operation, NSError *error) { | |
NSLog(@"error:%@",error); | |
}]; | |
requestOperation.responseSerializer = [AFJSONResponseSerializer serializer]; | |
return requestOperation; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment