Yuvaraj.M
Yuvaraj.M

Reputation: 9801

How to get find and get URL in a NSString in iPhone?

I have a text with http:// in NSString. I want to get that http link from the NSString. How can i get the link/url from the string? Eg: 'Stack over flow is very useful link for the beginners https://stackoverflow.com/'. I want to get the 'https://stackoverflow.com/' from the text. How can i do this? Thanks in advance.

Upvotes: 1

Views: 2826

Answers (3)

Abizern
Abizern

Reputation: 150755

Rather than splitting the string into an array and messing about that way, you can just search for the substring beginning with @"http://":

NSString *str = @"Stack over flow is very useful link for the beginners http://stackoverflow.com/";
// get the range of the substring starting with @"http://"
NSRange rng = [str rangeOfString:@"http://" options:NSCaseInsensitiveSearch];

// Set up the NSURL variable to hold the created URL
NSURL *newURL = nil;

// Make sure that we actually have found the substring
if (rng.location == NSNotFound) {
    NSLog(@"URL not found");
    // newURL is initialised to nil already so nothing more to do.
} else {
    // Get the substring from the start of the found substring to the end.
    NSString *urlString = [str substringFromIndex:rng.location];

    // Turn the string into an URL and put it into the declared variable
    newURL = [NSURL URLWithString:urlString];
}

Upvotes: 4

Yama
Yama

Reputation: 2649

try this :

nsstring *str = @"Stack over flow is very useful link for the beginners http://stackoverflow.com/";

nsstring *http = @"http";
nsarray *arrURL = [str componentsSeparatedByString:@"http"];

this will give two objects in the nsarray. 1st object will be having:Stack over flow is very useful link for the beginners and 2nd will be : ://stackoverflow.com/ (i guess)

then you can do like:

  NSString *u = [arrURL lastObject];

then do like:

nsstring *http = [http stringByAppendingFormat:@"%@",u];

Quite a lengthy,but i think that would work for you. Hope that helps you.

Upvotes: 1

Cyprian
Cyprian

Reputation: 9451

I am not sure what you exactly mean by link but if you want to convert your NSString to NSURL than you can do the following:

NSString *urlString = @"http://somepage.com";
NSURL *url = [NSURL URLWithString:urlString];

EDIT

This is how to get all URLs in a given NSString:

NSString *str = @"This is a grate website http://xxx.xxx/xxx you must check it out"; 

NSArray *arrString = [str componentsSeparatedByString:@" "];

for(int i=0; i<arrString.count;i++){
    if([[arrString objectAtIndex:i] rangeOfString:@"http://"].location != NSNotFound)
        NSLog(@"%@", [arrString objectAtIndex:i]);
}

Upvotes: 8

Related Questions