NSRange:rangeOfString在AFHTTPRequestOperation的成功块中抛出异常

时间:2014-01-15 16:58:30

标签: ios iphone afnetworking

我正在尝试在<之间获取一个字符串>标签。在AFHTTPRequestOperation的成功块中调用“rangeOfString”方法时,应用程序抛出异常。当我从成功块中调用rangeOfString方法时,它可以正常工作。

...
...
   NSString *Url = [NSString stringWithFormat:@"%@%@", BaseURLString, @"?q=services/session/token"];
[manager GET:Url parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"CSRF Token: %@", responseObject);
    //save CSRFToken to keychain
    NSString *response = (NSString *) responseObject;
//below line throws a NSInvalidArgument exception.
    NSRange range1 =  [response rangeOfString:@"<"];
    NSLog(@"range = %d", range1);
    dispatch_semaphore_signal(semaphore);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
    dispatch_semaphore_signal(semaphore);

}];

它给出了以下错误:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFData rangeOfString:]: unrecognized selector sent to instance 0xd12ba50'
*** First throw call stack:
(
0   CoreFoundation                      0x01e325e4 __exceptionPreprocess + 180
1   libobjc.A.dylib                     0x01bb58b6 objc_exception_throw + 44
2   CoreFoundation                      0x01ecf903 -[NSObject(NSObject) doesNotRecognizeSelector:] + 275
3   CoreFoundation                      0x01e2290b ___forwarding___ + 1019
4   CoreFoundation                      0x01e224ee _CF_forwarding_prep_0 + 14
5   vd                                  0x00003287 __58-[VDLoginHTTPClient getCSRFTokenWithUserName:andPassword:]_block_invoke + 167

这可能是什么问题? 此致...

2 个答案:

答案 0 :(得分:2)

您在NSData上调用此消息而不在NSString上。

你正在向NSString *转换responseObject - 这是错误的 - 可能你有NSData - 检查responseObject的类型并将其正确转换为NSString * - 而不是通过(NSString *)强制转换它。

如果你有NSData,请使用:

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

而不是:

NSString *response = (NSString *) responseObject;

答案 1 :(得分:1)

响应是NSData而不是NSString因此没有“&lt;”这样的字符在回应中。请尝试以下

NSString *response = [[NSString alloc] initWithData:responseObject
                                 encoding:NSUTF8StringEncoding]; 
NSRange range1 =  [response rangeOfString:@"<"];