How to URL encode a string (NSString) in iPhone?

When developing API based web applications we definitely need to interect with Multiple web services and URLs. The url may contain special character, search terms, queries, headers and many other things depending on the service we need. That’s why we need to have some kind of encoding so that the URL we are creating and the URL being called are same.

To achieve the same with Objective C we can use −

#import "NSString+URLEncoding.h"
@implementation NSString (URLEncoding)
-(NSString *)urlEncodeUsingEncoding:(NSStringEncoding)encoding {
   return (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
   (CFStringRef)self, NULL, (CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ", CFStringConvertNSStringEncodingToEncoding(encoding));

Another way to achieve URL encoding in Objective C is −

NSString *sUrl = @" name";
NSString *encod = [sUrl stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];

Similarly, URL encoding can be achieved in Swift like −

func getURL(str: String ) {
   return str.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)

Which is going to return an encoded URL string and can be used like,

var sURL = " name"

Which will print the following as a result. name

Updated on: 27-Jun-2020


Kickstart Your Career

Get certified by completing the course

Get Started