How can I get just the TLD of an NSURL? - ios

For example:
"http://www.youtube.com" --> ".com"
"http://www.google.com.gr" --> ".com.gr"
"https://made.in.china.chinesewebsite.닷컴" --> ".닷컴"
The host of a URL is a dead-end.
NSURL *URL;
[URL host];

Get the host of the url, break it up at the . delimiter, and take the last component.
- (NSString *) tldOfURL: NSURL *theURL; {
NSString *host = theURL.host;
NSArray *parts = [host componentsSeparatedByString: #"."];
if parts.count < 2 {
return nil;
}
return parts.lastObject;
}
At first my answer was to use NSURLComponents, as in most cases that class does all the heavy lifting for you, but it looks like it doesn't have a mechanism for extracting the TLD.
Note that the above will return nil if the host name does not contain at least one period (.) and will return an empty string if the host ends with a period. Both of these cases should be treated as errors.
P.S. I'm starting to get rusty at Objective-C syntax. Hard to believe, given how many years I's spent writing Objective-C!

Related

ios8 to validate urlField? [duplicate]

Help me to write the code like "if my string is a valid URL do smth"
Is it possible to write this in a couple strings of code?
I will assume that by URL, you are referring to a string identifying a internet resource location.
If you have an idea about the format of the input string , then why not manually check if the string starts with http://, https:// or any other scheme you need. If you expect other protocols, you can also add them to the check list (e.g. ftp://, mailto://, etc)
if ([myString hasPrefix:#"http://"] || [myString hasPrefix:#"https://"])
{
// do something
}
If you are looking for a more solid solution and detect any kind of URL scheme, then you should use a regular expression.
As a side note, the NSURL class is designed to express any kind of resource location (not just internet resources). That is why, strings like img/demo.jpg or file://bla/bla/bla/demo.jpg can be transformed into NSURL objects.
However, according to the documentation the [NSURL URLWithString] should return nil if the input string is not a valid internet resource string. In practice it doesn't.
+ (BOOL)validateUrlString:(NSString*)urlString
{
if (!urlString)
{
return NO;
}
NSDataDetector *linkDetector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:nil];
NSRange urlStringRange = NSMakeRange(0, [urlString length]);
NSMatchingOptions matchingOptions = 0;
if (1 != [linkDetector numberOfMatchesInString:urlString options:matchingOptions range:urlStringRange])
{
return NO;
}
NSTextCheckingResult *checkingResult = [linkDetector firstMatchInString:urlString options:matchingOptions range:urlStringRange];
return checkingResult.resultType == NSTextCheckingTypeLink
&& NSEqualRanges(checkingResult.range, urlStringRange);
}
I used this solution which is apparently a better and less complex check than a Regex check -
- (BOOL)isURL:(NSString *)inputString
{
NSURL *candidateURL = [NSURL URLWithString:inputString];
return candidateURL && candidateURL.scheme && candidateURL.host;
}
Try to create NSUrl with it, and see if it returns non-nil result.
if ([NSURL URLWithString:text]) {
// valid URL
}
else {
// invalid URL
}

Get position of NSString in string - iOS

I am developing an iOS app and one of the things I need to do it to go over URLs and replace the first protocol section with my own custom protocol.
How can I delete the first few characters of a NSString before the "://"?
So for example I need convert the following:
http://website.com --> cstp://website.com
ftp://website.com --> oftp://website.com
https://website.com --> ctcps://website.com
The main problem I face, is that I can't just delete the first 'x' number of characters from the URL string. I have to detect how many characters there are till the "://" characters are reached.
So how can I count how many characters there are from that start of the string to the "://" characters?
Once I know this, I can then simply do the following to delete the characters:
int counter = ... number of characters ...
NSString *newAddress = [webURL substringFromIndex:counter];
Thanks for your time, Dan.
http://website.com is a URL, and http is the scheme part of the URL. Instead of string manipulation I would recommend to use the
NSURLComponents class which is made exactly for this purpose: inspect, create and modify URLs:
NSString *originalURL = #"http://website.com";
NSURLComponents *urlcomp = [[NSURLComponents alloc] initWithString:originalURL];
if ([urlcomp.scheme isEqualToString:#"http"]) {
urlcomp.scheme = #"cstp";
} else if ([urlcomp.scheme isEqualToString:#"ftp"]) {
urlcomp.scheme = #"otfp";
}
// ... handle remaining cases ...
NSString *modifiedURL = [urlcomp string];
NSLog(#"%#", modifiedURL); // cstp://website.com
If the number of cases grows then a dictionary mapping is easier to
manage:
NSDictionary *schemesMapping = #{
#"http" : #"cstp",
#"ftp" : #"otfp"
#"https" : #"ctcps" };
NSURLComponents *urlcomp = [[NSURLComponents alloc] initWithString:originalURL];
NSString *newScheme = schemesMapping[urlcomp.scheme];
if (newScheme != nil) {
urlcomp.scheme = newScheme;
}
NSString *modifiedURL = [urlcomp string];
You can use:
NSRange range = [urlString rangeOfString:#"://"];
range.location will give you the first index from where the "://" starts and you can use it as:
NSString *newAddress = [urlString substringFromIndex:range.location];
and append your prefix:
NSString *finalAddress = [NSString stringWithFormat:#"%#%#", prefixString, newAddress];

iOS : How to do proper URL encoding?

I'm unable to open a URL into UIWebView so I've seached & found that I need to encode URL, so I tried to encode it but, I've facing problem in URL encoding : My URL is http://somedomain.com/data/Témp%20Page%20-%20Open.html (It's not real URL).
I'm concerned with %20 that I tried to replace using stringByReplacingOccuranceOfString:#"" withString:#"" , it give me the URL I wanted like http://somedomain.com/data/Témp Page - Open.html However its not opening in UIWebView but amazingly it opens in Safari & FireFox perfect. Even I open unencoded URL its automatically converts and open the page I'm looking for.
I've google for URL encoding & it points me to different results I already checked but no results help me out!! I tried different functions answers in different URL encoding question but it just changed all special characters and make my URL like, http%3A%2F%2Fsomedomain.com%2Fdata%2FT... which can't open in UIWebView and even in any browser.
It gives the following Error Log in UIWebView delegate
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error { }
Error Code : 101
& Description : Error Domain=WebKitErrorDomain Code=101 "The operation couldn’t be completed. (WebKitErrorDomain error 101.)" UserInfo=0x6e4cf60 {}
The answer #Dhaval Vaishnani provided is only partially correct. This method treats the ?, = and & characters as not to be encoded, since they're valid in an URL. Thus, to encode an arbitrary string to be safely used as a part of an URL, you can't use this method. Instead you have to fall back to using CoreFoundation and CFURLRef:
NSString *unsafeString = #"this &string= confuses ? the InTeRwEbZ";
CFStringRef safeString = CFURLCreateStringByAddingPercentEscapes (
NULL,
(CFStringRef)unsafeString,
NULL,
CFSTR("/%&=?$#+-~#<>|\\*,.()[]{}^!"),
kCFStringEncodingUTF8
);
Don't forget to dispose of the ownership of the resulting string using CFRelease(safeString);.
Also, it seems that despite the title, OP is looking for decoding and not encoding a string. CFURLRef has another, similar function call to be used for that:
NSString *escapedString = #"%32%65BCDEFGH";
CFStringRef unescapedString = CFURLCreateStringByReplacingPercentEscapesUsingEncoding (
NULL,
(CFStringRef)escapedString,
CFSTR(""),
kCFStringEncodingUTF8
);
Again, don't forget proper memory management.
I did some tests and I think the problem is not really with the UIWebView but instead that NSURL won't accept the URL because of the é in "Témp" is not encoded properly. This will cause +[NSURLRequest requestWithURL:] and -[NSURL URLWithString:] to return nil as the string contains a malformed URL. I guess that you then end up using a nil request with -[UIViewWeb loadRequest:] which is no good.
Example:
NSLog(#"URL with é: %#", [NSURL URLWithString:#"http://host/Témp"]);
NSLog(#"URL with encoded é: %#", [NSURL URLWithString:#"http://host/T%C3%A9mp"]);
Output:
2012-10-02 12:02:56.366 test[73164:c07] URL with é: (null)
2012-10-02 12:02:56.368 test[73164:c07] URL with encoded é: http://host/T%C3%A9mp
If you really really want to borrow the graceful handling of malformed URLs that WebKit has and don't want to implement it yourself you can do something like this but it is very ugly:
UIWebView *webView = [[[UIWebView alloc]
initWithFrame:self.view.frame]
autorelease];
NSString *url = #"http://www.httpdump.com/texis/browserinfo/Témp.html";
[webView loadHTMLString:[NSString stringWithFormat:
#"<script>window.location=%#;</script>",
[[[NSString alloc]
initWithData:[NSJSONSerialization
dataWithJSONObject:url
options:NSJSONReadingAllowFragments
error:NULL]
encoding:NSUTF8StringEncoding]
autorelease]]
baseURL:nil];
The most straightforward way is to use:
NSString *encodedString = [rawString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
iDhaval was close, but he was doing it the other way around (decoding instead of encoding).
Anand's way would work, but you'll most likely have to replace more characters than spaces and new lines. See the reference here:
http://en.wikipedia.org/wiki/Percent-encoding#Percent-encoding_reserved_characters
Hope that helps.
It's very simple to encode the URL in iPhone. It is as following
NSString* strURL = #"http://somedomain.com/data/Témp Page - Open.html";
NSURL* url = [NSURL URLWithString:[strURL stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
It's a perfect way to encode the URL, I am using it and it's perfectly work with me.
Hope it will help you!!!
This may useful to someone who's reach to this question for URL encoding, as my question likely different which has been solved and accepted, this is the way I used to do encoding,
-(NSString *)encodeURL:(NSString *)urlString
{
CFStringRef newString = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)urlString, NULL, CFSTR("!*'();:#&=+#,/?#[]"), kCFStringEncodingUTF8);
return (NSString *)CFBridgingRelease(newString);
}
You can try this
NSString *url = #"http://www.abc.com/param=Hi how are you";
NSString* encodedUrl = [url stringByAddingPercentEscapesUsingEncoding:
NSASCIIStringEncoding];
I think this will work for you
[strUrl stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.URLQueryAllowedCharacterSet]
the Native method for URL Encoding.
Swift 4.x
let originalString = "https://www.somedomain.com/folder/some cool file.jpg"
let escapedString = originalString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
print(escapedString!)
You probably need to break the URL down into it's constituent parts and then URL encode the host and path but not the scheme. Then put it back together again.
Create an NSURL with the string and then use the methods on it such as host, scheme, path, query, etc to pull it apart. Then use CFURLCreateStringByAddingPercentEscapes to encode the parts and then you can put them back together again into a new NSURL.
can you please Try this out.
//yourURL contains your Encoded URL
yourURL = [yourURL stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
yourURL = [yourURL stringByReplacingOccurrencesOfString:#"\n" withString:#""];
NSLog(#"Keyword:%# is this",yourURL);
I am not sure,but I have solved using this in my case.
Hope this will solve yours.

IOS affiliate link shorten with bit.ly not working

I want to use bit.ly to track my itunes affiliate links.
I get affiliate links from http://target.georiot.com.
It works when oppening the direct link (going to itunes).
But when i shorten the affiliate link with bitly, it doesn't go on the same page.
Here is the code for getting the shorten url:
NSString *longURL = link;
NSString *bitlyRequestURLString = [NSString stringWithFormat:#"http://api.bit.ly/shorten?version=2.0.1&format=xml&login=%#&apiKey=%#&longUrl=%#",
#"myappname",
#"myappidentifier",
longURL];
NSURL *bitlyURL = [NSURL URLWithString:bitlyRequestURLString];
// get the short URL from bit.ly
NSError *error;
NSString *response = [NSString stringWithContentsOfURL:bitlyURL encoding:NSUTF8StringEncoding error:&error];
NSString *shortURL = #"";
NSArray *responseParts = [response componentsSeparatedByString:#"<shortUrl>"];
if ([responseParts count] > 1) {
NSString *responsePart = [responseParts objectAtIndex:1];
responseParts = [responsePart componentsSeparatedByString:#"</shortUrl>"];
if ([responseParts count] > 0) {
shortURL = [responseParts objectAtIndex:0];
}
}
Last redirect link goes someting like "http://phobos.apple.com/WebObjects/...."
Any Ideas?
Thanks
You probably need to URL encode your longURL before sending it in the query string to bit.ly
You can use the NSString method stringByAddingPercentEscapesUsingEncoding:
NSString *longURL = [link stringByAddingPercentEscapesUsingEncoding:
NSASCIIStringEncoding];
NSString *bitlyRequestURLString = [NSString stringWithFormat:#"http://api.bit.ly/shorten?version=2.0.1&format=xml&login=%#&apiKey=%#&longUrl=%#",
#"myappname",
#"myappidentifier",
longURL];
I just tried using the bit.ly REST API to create a short url and the URL returned works as expected, see below. It looks like the prior answer suggesting encoding was on target, and standard url encoding (percent encoding, such as http://meyerweb.com/eric/tools/dencoder/) seems to do the trick.
This call (with proper API key):
https://api-ssl.bitly.com/v3/shorten?login=georiot&apiKey=R_MY_API_KEY_HERE&longUrl=http%3A%2F%2Ftarget.georiot.com%2FProxy.ashx%3Fgrid%3D64%26id%3D8i%2FET44NjHw%26offerid%3D146261%26type%3D3%26subid%3D0%26tmpid%3D1826%26RD_PARM1%3Dhttp%3A%2F%2Fitunes.apple.com%2Fus%2Falbum%2Fmetallica%2Fid278116714%3Fuo%3D4%26partnerId%3D30%2F&format=json
Returned:
{ "status_code": 200, "status_txt": "OK", "data": { "long_url": "http://target.georiot.com/Proxy.ashx?grid=64&id=8i/ET44NjHw&offerid=146261&type=3&subid=0&tmpid=1826&RD_PARM1=http://itunes.apple.com/us/album/metallica/id278116714?uo=4&partnerId=30/", "url": "http://bit.ly/zR6uzb", "hash": "zR6uzb", "global_hash": "wFpgG2", "new_hash": 1 } }
The result url works as expected (after removing the escape /'s): http:\bit.ly\zR6uzb
At GeoRiot, we have also recently added a new integrated url shortener which might be of interest to you, however we haven't exposed an API for it quite yet. If you are interested in giving this a shot when we have it available, please let us know. The big benefit here is that the extra redirect between bit.ly and georiot would be removed, speeding up the response time for your users quite a bit.
Anyway, its been a while since the original post, so hopefully you got this figured out. If not let us know and we'll help where we can!

Search NSString in line from file

Is it possible to make a function that searchs a string for an exact substring so that it will only 'return true' if the exact string if found, not as part of a larger word?
NSString* search = #"tele";
NSString* stringOne = #"telephone";
NSString* stringTwo = #"tele phone";
NSString* stringThree = #"phone tele";
What I mean is: Is it possible to search for a string in a way that the NSString 'search' would be found in strings Two and Three, but not One?
Try using the following function in the NSString class:
- (NSRange)rangeOfString:(NSString *)aString
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nsstring_Class/Reference/NSString.html
Simplest approach is to append blanks (or whatever your separators are) to front and rear of both strings, then do the search.

Resources