简体   繁体   中英

NSRange:rangeOfString throws an exception in AFHTTPRequestOperation's success block

I'm trying to get a string between < > tags. Application throws an exception when the "rangeOfString" method is called in AFHTTPRequestOperation's success block. When I call the rangeOfString method out of the success block it works properly.

...
...
   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);

}];

It gives below error:

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

What could be the problem here? Regards...

You are calling this message on NSData not on NSString.

You are casting responseObject to NSString* - which is wrong - probably you have NSData there - check the type of responseObject and convert it to NSString * properly - not by hard casting it with (NSString*).

If you have NSData, use that:

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

instead of:

NSString *response = (NSString *) responseObject;

The response is NSData and not NSString hence there is no such character as "<" in the response. Try the following

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM