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.
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]);
}
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];
}
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.
Related
I am trying to remove just the last part of the url, Its a FTP URL.
Suppose, I have a URL like: > ftp://ftp.abc.com/public_html/somefolder/. After removing the last portion I should have it as: ftp://ftp.abc.com/public_html/.
I have tried using stringByDeletingLastPathComponenet and URLByDeletingLastPathComponent, but they dont remove the last portion correctly. They change the entire looks of the url.
for instance, after using the above said methods, here is the URL format i get ftp:/ftp.abc.com/public_html/. It removes one "/" in "ftp://", which is crashing my program.
How is it possible to removve just the last part without disturbing the rest of the URL ?
UPDATE:
NSURL * stringUrl = [NSURL URLWithString:string];
NSURL * urlByRemovingLastComponent = [stringUrl URLByDeletingLastPathComponent];
NSLog(#"%#", urlByRemovingLastComponent);
Using above code, I get the output as :- ftp:/ftp.abc.com/public_html/
Hmm. URLByDeletingLastPathComponent works perfectly given the above input.
NSURL *url = [NSURL URLWithString:#"ftp://ftp.abc.com/public_html/somefolder/"];
NSLog(#"%#", [url URLByDeletingLastPathComponent]);
returns
ftp://ftp.abc.com/public_html/
Do you have some sample code that is yielding improper results?
Max
Now try
NSString* filePath = #"ftp://ftp.abc.com/public_html/somefolder/.";
NSArray* pathComponents = [filePath pathComponents];
NSLog(#"\n\npath=%#",pathComponents);
if ([pathComponents count] > 2) {
NSArray* lastTwoArray = [pathComponents subarrayWithRange:NSMakeRange([pathComponents count]-2,2)];
NSString* lastTwoPath = [NSString pathWithComponents:lastTwoArray];
NSLog(#"\n\nlastTwoArray=%#",lastTwoPath);
NSArray *listItems = [filePath componentsSeparatedByString:lastTwoPath];
NSLog(#"\n\nlist item 0=%#",[listItems objectAtIndex:0]);
}
output
path=(
"ftp:",
"ftp.abc.com",
"public_html",
somefolder,
"."
)
lastTwoArray =somefolder/.
list item 0 =ftp://ftp.abc.com/public_html/
An example of how to extract the last part of NSURL. In this case the location of the file. Sqlite core data
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:#"CoreAPI.sqlite"];
NSString *localPath = [storeURL absoluteString];
NSArray* pathComponents = [localPath pathComponents];
NSLog(#"%#",[pathComponents objectAtIndex:6]);
NSString * nombre = [NSString stringWithFormat:#"%#", [pathComponents objectAtIndex:6]];
This code returns me the name of the file CoreAPI.sqlite
for(int i= 0 ;i<[urlsArrray count]; i++)
{
NSString *urlString = [urlsArrray objectAtIndex:i];
NSString *escapedUrlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:escapedUrlString];
NSString *urlstring1 = [url absoluteString];
NSArray *parts = [urlstring1 componentsSeparatedByString:#"/"];
NSString *fileName = [parts objectAtIndex:[parts count]-1];
NSMutableString *tempString = [NSMutableString stringWithString:fileName];
// [tempString replaceCharactersInRange:[tempString rangeOfString:#"%20"] withString:#" "];
NSLog(#"file name in temp string: %# word name: %#", tempString, wordNameDB);
NSRange match = [tempString rangeOfString:wordNameDB];
if(match.location != NSNotFound)
{
NSLog(#"match found at %u", match.location);
isAvailable = YES;
break;
}
Hi friends, now my problem is i am getting file name from server..., if file name is having any spaces then it replace '%20' ( i.e ex: "hello world" is actual name but i am getting file name like: "hello%20world") .
1. I am not sure all file names having spaces.
2. And also i am not sure a file may have only one space
so first i have to check the file is having spaces or not, if have then i want to replace all "%20" with #" " string. Please give me any suggestions or code snippets.
OR " THERE IA ANY OTHER WAY TO READ FILE NAMES WITHOUT GETTING '%20' IN THE PLACE OF SPACE(#" ")..... thank you
If you have your file name stored in fileName param, you can use the following:
fileName = [fileName stringByReplacingOccurrencesOfString:#"%20" withString:#" "];
The above code will replace all "%20" with " ". If there are no "%20" in the fileName, you will get back the same string.
Correction:
I was confused with stringByAddingPercentEscapesUsingEncoding mentioned in code and thought you have already used stringByReplacingPercentEscapesUsingEncoding. If you are not using stringByReplacingPercentEscapesUsingEncoding method, you should use that in this case. The above code is useful, only if that is not able to remove any particular string which you want to replace.
What you need is replacing the escape charcters, according to the encoding.
Use this and all your spaces and other URL encoded characters will be converted to what you need.
[#"yourString" stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
THERE IA ANY OTHER WAY TO READ FILE NAMES WITHOUT GETTING '%20' IN THE PLACE OF SPACE(#" ")
Yes, use this:
NSString *newString = [yourstring stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
Use this to remove spaces ..
urlString = [urlString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
You seem to already have a valid NSURL object representing the file. Getting the filename from a URL is easy:
...
NSURL *url = [NSURL URLWithString:escapedUrlString];
NSString *path = [url path];
NSString *filename = [path lastPathComponent];
No fiddling with unescaping percent escapes, URL parsing, and other error prone stuff.
So I check if the string starts with "http://" using the code below, and then I want to add "http://" so that I'm able to open the page in UIWebView.
NSString *firstString = [NSString stringWithFormat:#"%#", URL.text];
NSString *check = [NSString stringWithFormat:#"%#", #"http://"];
if (firstString != check) {
NSString *newString = [NSString stringWithFormat:#"http://%#", URL.text];
newString = [newString substringWithRange:NSMakeRange(7, newString.length - 7)];
URL.text = newString;
}
[WebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:URL.text]]];`
This doesn't work for some reason.
Do you know why?
Somebody posted as I was writing, but either way, here's an answer:
You are making this too difficult. You simply need to use hasPrefix to check for "http". As an example, I use this for my unified search/url bar.
- (IBAction)go:(id)sender {
NSString *inputString = [searchField stringValue];
NSString *outputString = [inputString stringByReplacingOccurrencesOfString:#" " withString:#"+"];
if ([inputString hasPrefix:#"http://"]) {
//Has Prefix
[[webView mainFrame] loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:inputString]]];
}
else
{
//Does not have prefix. Do what you want here. I google it.
NSString *googleString = #"http://google.com/search?q=";
NSString *searchString = [NSString stringWithFormat:#"%#%#", googleString, outputString];
[[webView mainFrame] loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:searchString]]];
}
}
That is for googling instead, you could keep using NSString *newString = [NSString stringWithFormat:#"http://%#", URL.text];
You could add a few more checks as well if you wanted to. Good luck!
firstString != check checks to see if both objects point to the same location in memory. [firstString isEqualToString:check] checks if the two strings are equal. However, what you most likely want to do is if(![firstString hasPrefix:check]). This will check to make sure firstString does not start with check, then you can append check to the start of it. Alternatively, you can do firstString = [firstString stringByReplacingOccurrencesOfString:#"http://" withString:#""];, and then you know it will never start with #"http://"
Try printing what URL.text is before the loadRequest line via NSLog(#"%#",URL.text);
Also the preferred check condition would be if (![firstString isEqualToString:check]) {}
I have an NSMutable dictionary that contains file IDs and their filename+extension in the simple form of fileone.doc or filetwo.pdf. I need to determine what type of file it is to correctly display a related icon in my UITableView. Here is what I have done so far.
NSString *docInfo = [NSString stringWithFormat:#"%d", indexPath.row]; //Determine what cell we are formatting
NSString *fileType = [contentFiles objectForKey:docInfo]; //Store the file name in a string
I wrote two regex to determine what type of file I'm looking at, but they never return a positive result. I haven't used regex in iOS programming before, so I'm not entirely sure if I'm doing it right, but I basically copied the code from the Class Description page.
NSError *error = NULL;
NSRegularExpression *regexPDF = [NSRegularExpression regularExpressionWithPattern:#"/^.*\\.pdf$/" options:NSRegularExpressionCaseInsensitive error:&error];
NSRegularExpression *regexDOC = [NSRegularExpression regularExpressionWithPattern:#"/^.*\\.(doc|docx)$/" options:NSRegularExpressionCaseInsensitive error:&error];
NSUInteger numMatch = [regexPDF numberOfMatchesInString:fileType options:0 range:NSMakeRange(0, [fileType length])];
NSLog(#"How many matches were found? %#", numMatch);
My questions would be, is there an easier way to do this? If not, are my regex incorrect? And finally if I have to use this, is it costly in run time? I don't know what the average amount of files a user will have will be.
Thank you.
You're looking for [fileType pathExtension]
NSString Documentation: pathExtension
//NSURL *url = [NSURL URLWithString: fileType];
NSLog(#"extension: %#", [fileType pathExtension]);
Edit you can use pathExtension on NSString
Thanks to David Barry
Try this :
NSString *fileName = #"resume.doc";
NSString *ext = [fileName pathExtension];
Try this, it works for me.
NSString *fileName = #"yourFileName.pdf";
NSString *ext = [fileName pathExtension];
Documentation here for NSString pathExtension
Try using [fileType pathExtension] to get the extension of the file.
In Swift 3 you could use an extension:
extension String {
public func getExtension() -> String? {
let ext = (self as NSString).pathExtension
if ext.isEmpty {
return nil
}
return ext
}
}
I have some source code to get the file name of an url
for example:
http://www.google.com/a.pdf
I hope to get a.pdf
because the way to join 2 NSStrings I can get is 'appendString' which only for adding a string at right side, so I planned to check each char one by one from the right side of string 'http://www.google.com/a.pdf', when it reach at the char '/', stop the checking, return string fdp.a , after that I change fdp.a to a.pdf
source codes are below
-(NSMutableString *) getSubStringAfterH : originalString:(NSString *)s0
{
NSInteger i,l;
l=[s0 length];
NSMutableString *h=[[NSMutableString alloc] init];
NSMutableString *ttt=[[NSMutableString alloc] init ];
for(i=l-1;i>=0;i--) //check each char one by one from the right side of string 'http://www.google.com/a.pdf', when it reach at the char '/', stop
{
ttt=[s0 substringWithRange:NSMakeRange(i, 1)];
if([ttt isEqualToString:#"/"])
{
break;
}
else
{
[h appendString:ttt];
}
}
[ttt release];
NSMutableString *h1=[[[NSMutableString alloc] initWithFormat:#""] autorelease];
for (i=[h length]-1;i>=0;i--)
{
NSMutableString *t1=[[NSMutableString alloc] init ];
t1=[h substringWithRange:NSMakeRange(i, 1)];
[h1 appendString:t1];
[t1 release];
}
[h release];
return h1;
}
h1 can reuturn the coorect string a.pdf, but if it returns to the codes where it was called, after a while system reports
'double free
*** set a breakpoint in malloc_error_break to debug'
I checked a long time and foudn that if I removed the code
ttt=[s0 substringWithRange:NSMakeRange(i, 1)];
everything will be Ok (of course getSubStringAfterH can not returns the corrent result I expected.), no error reported.
I try to fix the bug a few hours, but still no clue.
Welcome any comment
Thanks
interdev
The following line does the job if url is a NSString:
NSString *filename = [url lastPathComponent];
If url is a NSURL, then the following does the job:
NSString *filename = [[url path] lastPathComponent];
Try this:
Edit: from blow comment
NSString *url = #"http://www.google.com/a.pdf";
NSArray *parts = [url componentsSeparatedByString:#"/"];
NSString *filename = [parts lastObject];
I think if you have already had the NSURL object, there is lastPathComponent method available from the iOS 4 onwards.
NSURL *url = [NSURL URLWithString:#"http://www.google.com/a.pdf"];
NSString *filename = [url lastPathComponent];
Swift 3
Let's say that your url is http://www.google.com/a.pdf
let filename = url.lastPathComponent
\\filename = "a.pdf"
This is more error free and meant for getting the localized name in the URL.
NSString *localizedName = nil;
[url getResourceValue:&localizedName forKey:NSURLLocalizedNameKey error:NULL];
I haven't tried this yet, but it seems like you might be trying to do this the hard way. The iPhone libraries have the NSURL class, and I imagine that you could simply do:
NSString *url = [NSURL URLWithString:#"http://www.google.com/a.pdf"];
NSString *path = [url path];
Definitely look for a built in function. The libraries have far more testing and will handle the edge cases better than anything you or I will write in an hour or two (generally speaking).