Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS how to deal with spaces or special characters passed to AFHTTPSessionManager GET method?

I have an instance of AFHTTPSessionManager responsible for making a GET request. One of parameters in the request - name can have spaces in it or potentially other characters that might not be acceptable in a URL.

I see that AFHTTPSessionManager does not automatically replace spaces with the appropriate %symbol, so the request below will fail. How can I process my string to turn it into a URL compatible string? test user to test%20user

I can do string by replacing occurences of string, but am looking for a more generic method to handle all not-url safe characters.

NSURL* baseURL = [NSURL URLWithString:[APP_DELEGATE hostString]];

AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:baseURL];

//is there a way for me
NSString* path = @"user/?name=test user"

[manager GET:path parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
    DLog(@"Success: %@",responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
    DLog(@"Failure:  %@",error);
}];
like image 570
Alex Stone Avatar asked Feb 13 '23 04:02

Alex Stone


1 Answers

I think the method you are looking for is

- (NSString *)stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)encoding

That is:

NSString* path = [@"user/?name=test user" stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];

In your case, you may have to only apply the percent encoding to the actual values that may contain invalid characters (i.e. "test user")

another option is to use the NSDictionary offered by AFNetworking's get method. Using this option you could create an nsdictionary with the key/value pair {"name":"test user"} then pass that in the AF's get method. AF will add this as a querystring onto your get path.

NSString* path = @"user";
NSDictionary* params = [NSDictionary dictionaryWithObject:@"test user" forKey:@"name"];
[manager GET:path parameters:params success...
like image 145
Aaron Avatar answered Feb 16 '23 03:02

Aaron