将ASIHTTPRequest更改为AFNetworking 2以获取简单的URL请求

时间:2014-08-20 06:59:48

标签: ios asihttprequest afnetworking-2

我正在处理另一位开发者创建的iOS应用的更新。 他们使用ASIHTTPRequest,但我认为我应该切换到AFNetworking,以便整个应用程序可以是ARC。我没有编写网络应用程序的经验,所以我发现AFNetworking 2非常混乱。在我的项目中包含文件并使用#import" AFNetworking.h"添加标题后有没有一种简单的方法来调整RSSReader.m中的以下方法,以便它可以工作?

以下是现有代码:

-(NSArray*)readUTF16LEFeed:(NSURL*) urlToRead{
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:urlToRead];
[request startSynchronous];
NSError *error = [request error];
if (!error) {
lastModified = [NSDate date];
NSData *response = [request responseData];//UTF-16LE
NSString* responseString = [[NSString alloc] initWithData:response encoding: NSUTF16LittleEndianStringEncoding];
DLog(@"string is: %@",responseString);
responseString = [responseString stringByReplacingOccurrencesOfString:@"ISO-8859-1" withString:@"UTF16-LE"];
NSData* data = [responseString dataUsingEncoding:NSUTF16LittleEndianStringEncoding];
return [self parseNamesFromXML:data];
}
return nil;
}

1 个答案:

答案 0 :(得分:0)

添加导入

#import "AFHTTPRequestOperationManager+AutoRetry.h"

并尝试使用此代码

-(void)readUTF16LEFeed:(NSString*) urlToRead{
    AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
    void (^successBlock)(AFHTTPRequestOperation * operation, id responseObject) = ^(AFHTTPRequestOperation * operation, id responseObject){
        //work with response
        //NSData *response = [request responseData];//UTF-16LE
        NSString* responseString = [[NSString alloc] initWithData:responseObject encoding: NSUTF16LittleEndianStringEncoding];
        responseString = [responseString stringByReplacingOccurrencesOfString:@"ISO-8859-1" withString:@"UTF16-LE"];
        NSData* data = [responseString dataUsingEncoding:NSUTF16LittleEndianStringEncoding];

    };
    void (^failureBlock)(AFHTTPRequestOperation * operation, NSError * error) = ^(AFHTTPRequestOperation * operation, NSError * error){
        //if error do this
    };
    [manager GET:urlToRead parameters:nil success:successBlock failure:failureBlock autoRetry:5 retryInterval:2];
}