Thursday, September 13, 2018

Replace occurrences of space in URL

Some time developer face issue to validate or perfect in URL below code help you create a correct URL.

I want to replace the spaces with '%20'.


The correct format for replacing space from url is :
Objective C
NSString *urlString;//your url string.

urlString = [originalUrl stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
or
urlString = [originalUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
iOS 9 and later
urlString = [originalUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
Swift :
var originalUrl = "https://google.co.in"
var urlString :String = originalUrl.stringByReplacingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
ios 9 and later
var urlString :String = originalUrl.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
Swift 4
var urlString = originalString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)

No comments:

Post a Comment