Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make an NSURL with an encoded plus (%2B)

I need to pass a timestamp with a timezone offset in a GET request, e.g.,

2009-05-04T11:22:00+01:00

This looks like a two arguments "2009-05-04T11:22:00" and "01:00" to the receiving PHP script (over which I've no control).

NSURL doesn't encode plus signs, but if I make an NSURL using the string

2009-05-04T11:22:00%2B01:00

the url I end up with contains:

2009-05-04T11:22:00%252B01:00

Any ideas how I can preserve my encoded plus sign or just plain prevent NSURL from encoding anything?

like image 246
edoloughlin Avatar asked May 22 '09 15:05

edoloughlin


People also ask

How do you put a plus in a URL?

If you want a plus + symbol in the body you have to encode it as 2B . Literally as %2B ? Yes, %2B is what you want!

Can you have a plus in a URL?

Generally speaking, the plus sign is used as shorthand for a space in query parameters, but while it can be used in such a way in URLs, it isn't a good idea. The plus sign is sometimes transformed into a space or to “%20” which can cause problems for the spiders crawling your site, hence causing issues with indexation.

How do you add %20 to a URL?

Instead of encoding a space as “%20,” you can use the plus sign reserved character to represent a space. For example, the URL “http://www.example.com/products%20and%20services.html” can also be encoded as http://www.example.com/products+and+services.html.


2 Answers

What worked for me was doing the UTF8 conversion, then replacing the + sign with %2B:

NSString *urlString =
    [NSString stringWithFormat:@"%@/iphone/push/create?pn[token]=%@&pn[send_at]=%@",
     kHTTPURL, appDelegate.deviceAPNToken, [dateTimeToUse description]];

urlString =
    [[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
     stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"];
like image 177
anonymous Avatar answered Sep 28 '22 07:09

anonymous


The string should be URL encoded.

Here is a category for NSString that will help:

NSString+Additions.h

@interface NSString (Additions)

- (NSString *)stringByURLEncoding;

NSString+Additions.m

#import "NSString+Additions.h"

@implementation NSString (Additions)

- (NSString *)stringByURLEncoding {
    return (__bridge NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
                                                           (CFStringRef)self,
                                                           NULL,
                                                           (CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ",
                                                           CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
}
like image 44
Ric Santos Avatar answered Sep 28 '22 06:09

Ric Santos