UIWebView URL from String without http:// - iphone

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]) {}

Related

Remove last portion of the NSURL: iOS

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

Bad URL when creating NSURL

I am making request on server , having spaces in URL
http://xxxxxxxx.com/api/api.php?func=showAllwedsdwewsdsd&params[]=Saudi%20Arab&params[]=all
I was getting the error Bad URL so ,
I used
downloadURL = [downloadURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
but due this I am getting strange URL as
http://sdsdsdsdsdsd.com/api/api.php?func=showAllsdsd&params5262721536=Saudi 0X0P+0rabia&params5 8288=All
I am also using
downloadURL= [downloadURL stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
but again strange url like
http://xxxxxxxxx.com/api/api.php?func=showsdsdsd&params[]=Saudi 0X1.240DC0D824P-807rabia&params[]=All
Please help how can I solve this issue
Edit Pasting Big portion of code
PropertyXMLDownloader *download=[[PropertyXMLDownloader alloc]init];
[download setDelegate:self];
firstAppDelegate *del=(firstAppDelegate *)[[UIApplication sharedApplication]delegate];
NSLog(#"Country is %#",del.country);
NSLog(#"State is %#",del.state);
// del.country=[del.country stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
NSString *downloadURL=[NSString stringWithFormat:#"http://xxxxxxxx.com/api/api.php?func=showAll&params[]=Saudi Arabia&params[]=%#",#"all"];
// downloadURL= [downloadURL stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
//downloadURL = [downloadURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:#" "];
downloadURL = [[downloadURL componentsSeparatedByCharactersInSet: doNotWant] componentsJoinedByString:#"%20"];
NSLog(downloadURL);
[download startDownloading:downloadURL];
try this.
NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:#" "];
downloadURL = [[downloadURL componentsSeparatedByCharactersInSet: doNotWant] componentsJoinedByString:#"%20"];
Perhaps the %20 is being seen as a data argument, like %# or %g. Try defining the NSString using
NSString *urlString = [NSString stringWithFormat:#"http://xxxxxxxx.com/api/api.php?func=showAllwedsdwewsdsd&params[]=Saudi%20Arab&params[]=all"];
and you'll see a warning. 'Escaping' the percent sign by adding another in front of it:
NSString *urlString = [NSString stringWithFormat:#"http://xxxxxxxx.com/api/api.php?func=showAllwedsdwewsdsd&params[]=Saudi**%**%20Arab&params[]=all"];
and the warning goes away.
Your problem is this:
NSLog(downloadURL);
Try replacing it by:
NSLog(#"%#", downloadURL);
and everything will work.
You can use stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding and forget about all the workarounds.
(Explanation: since downloadURL contains % signs, it will not play well with NSLog, which expect a format string as its first argument, where % signs identify placeholders to be replaced).

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.
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.

How to combine two strings in Objective-C for an iPhone app

How can I combine "stringURL" and "stringSearch" together?
- (IBAction)search:(id)sender;{
stringURL = #"http://www.websitehere.com/index.php?s=";
stringSearch = search.text;
/* Something such as:
stringURL_ = stringURL + stringSearch */
[web loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:stringURL_]]];
}
Philippe gave a good example.
You can also use plain stringWithFormat: method.
NSString *combined = [NSString stringWithFormat:#"%#%#", stringURL, stringSearch];
This way you can manipulate string even more by putting somethig inbetween the strings like:
NSString *combined = [NSString stringWithFormat:#"%#/someMethod.php?%#", stringURL, stringSearch];
NSString* combinedString = [stringUrl stringByAppendingString: search.text];
NSString * combined = [stringURL stringByAppendingString:stringSearch];
Instead of stringByAppendingString:, you could also use
NSString *combined = [NSString stringWithFormat: #"%#%#",
stringURL, stringSearch];
This is especially interesting/convenient if you have more than one string to append. Otherwise, the stringbyAppendingString: method is probably the better choice.
You can use stringByAppendingString:
stringURL = [#"http://www.websitehere.com/index.php?s="
stringByAppendingString:search.text];
If you want to have some control about the format of the parameter you should assemble
your URL string with
[NSString stringWithFormat:#"http://www.websitehere.com/index.php?s=%#", search.text]
This solution is charming because you can append almost anything which can be inserted into a printf-style format.
I would not have given the answer of such general question.
There are many answers of same type question have already given. First find the answer of your question from existing question.
NSString* myURLString = [NSString stringWithFormat:#"http://www.websitehere.com/index.php?s=%#", search.text];

function to get the file name of an URL

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).