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);
}];
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With