IOS, how to handle spaces or special characters passed to AFHTTPSessionManager GET method?

I have an instance AFHTTPSessionManager

responsible for making a GET request. One of the parameters in the request name can contain spaces in it, or potentially other characters that might not be acceptable in the URL.

I see that it AFHTTPSessionManager

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

I can make a string by replacing the occurrences of the string, but I am looking for a more general method to handle all safe non-url 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);
}];

      

+3


source to share


3 answers


I think the method you are looking for is

- (NSString *)stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)encoding

      

I.e:

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

      



In your case, you may only need to apply percentage encoding to actual values, which may contain invalid characters (ie "test user")

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

NSString* path = @"user";
NSDictionary* params = [NSDictionary dictionaryWithObject:@"test user" forKey:@"name"];
[manager GET:path parameters:params success...

      

+6


source


I found the following method especially useful for encoding URLs appropriately:



- (NSString *)urlEncode:(NSString *)str {
    return (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)str, NULL, CFSTR("!*'();:@&=+$,/?%#[]"), kCFStringEncodingUTF8));
}

      

+2


source


0


source







All Articles