0

Let's say I have www.GOOgle.com/.......

I want to change it to www.google.com/....

and keep the rest of url as it is.

I have tried with NSURLComponents, but it didn't work.

// I am taking input from textfield and making the nsurl.

 NSURLComponents *components = [NSURLComponents componentsWithString: _textfield.text]; // input from textfield
[[components host] lowercaseString];
 NSURL *urlin = [components URL]; //but this gives, www.GOOgle.com

Any lead is appreciated.

Larme
  • 18,203
  • 5
  • 42
  • 69
backbencher
  • 89
  • 1
  • 8
  • why not `[_textfield.text lowercaseString];`before convert to `NSURL` – Reinier Melian Dec 21 '17 at 11:45
  • 2
    Why you need to covert url to lower case ? – Prashant Tukadiya Dec 21 '17 at 11:49
  • 2
    `[[components host] lowercaseString]` That's returning something, that doesn't modify it. It should be at least `[components setHost:[[components host] lowercaseString]];` Also, is `[components host]` nil, no? If you add `http://` to your string text, if may work then. See https://stackoverflow.com/questions/13130315/url-host-name-returns-null – Larme Dec 21 '17 at 11:50

3 Answers3

2

As @Larme Suggests you can use method to setHost in url

see below example

NSURLComponents *components = [NSURLComponents componentsWithString: @"https://sTackoverFlow.com/questions/47924276/how-to-convert-host-of-nsurl-to-lowercase"]; 
[components setHost:[components.host lowercaseString] ]; 
NSLog(@"%@",components.URL)

H ttps://stackoverflow.com/questions/47924276/how-to-convert-host-of-nsurl-to-lowercase


NOTE:

http:// is required to add in String otherwise you will get host nil eg https://www.sTackoverFlow.com/questions/47924276/how-to-convert-host-of-nsurl-to-lowercase it will work

while

www.sTackoverFlow.com/questions/47924276/how-to-convert-host-of-nsurl-to-lowercase

Will Not work

Prashant Tukadiya
  • 13,804
  • 3
  • 55
  • 78
0

If your string is only url then, you can try this,

let strURL = "http://GOogLe.Com/Testt/xyz"
let url = NSURL(string: strURL)
let domain: String = (url?.host)! //get your host name
print(domain) //GOogLe.Com

let str = strURL.replacingOccurrences(of: domain, with: domain.lowercased())
print(str) //http://google.com/Testt/xyz
rmaddy
  • 298,130
  • 40
  • 468
  • 517
Bhavi Lad
  • 207
  • 2
  • 7
  • Do not use `NSURL` in Swift. Use `URL`. – rmaddy Dec 21 '17 at 15:15
  • And this can fail since it is possible that the domain could be in the URL more than once but only the actual domain part of the URL should be changed. – rmaddy Dec 21 '17 at 15:17
-1
  1. Convert the string to lowercase.
  2. Then pass the converted string value to the componentsWithString method.

Sample: NSString *lowerCaseStringValue = [_textfield.text lowercaseString]; [NSURLComponents componentsWithString: lowerCaseStringValue];

rmaddy
  • 298,130
  • 40
  • 468
  • 517
GJDK
  • 693
  • 2
  • 7
  • 17