0

Possible Duplicate:
URL encode a NSString

I am trying to send strings with whitespaces like:

stack exchange

by

[[ApiClient sharedClient] getPath:[NSString stringWithFormat:@"/search/?q=%@", @"stack exchange"] parameters:nil success:^ ...

But I am getting

Error Domain=NSURLErrorDomain Code=-1000 "bad URL"

How can I solde this?

Community
  • 1
  • 1
Burak
  • 5,706
  • 20
  • 70
  • 110

2 Answers2

0

You are going to want to encode your url parameters.

// Add this to your class or universal class to be used
// Encode a string to embed in an URL.
NSString *encodeToPercentEscapeString(NSString *string) {
    return (__bridge NSString *)
    CFURLCreateStringByAddingPercentEscapes(NULL,
                                            (CFStringRef) string,
                                            NULL,
                                            (CFStringRef) @"!*'();:@&=+$,/?%#[]",
                                            kCFStringEncodingUTF8);
}

// now you can encode your parameters before adding to your url
NSString *urlParam = @"My custom text";

urlParam = encodeToPerecentEscapeString(urlParam);

// now you can use urlParam in any url parameter requirement
Bill Burgess
  • 14,054
  • 6
  • 49
  • 86
0

I made a sample project a while ago that shows the different ways you can escape strings in ObjC. It's on github

I ended up using something like this:

NSString *escapedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef) myString, NULL, CFSTR("!*()$&`:<>[]{}\"+#@/;=?\\^|~'%%,."), kCFStringEncodingUTF8));

This seemed to cover all the edge cases I could find.

Keith Smiley
  • 61,481
  • 12
  • 97
  • 110