See if a NSString is an website URL in objective-c - objective-c

How to find out if a NSString is an website URL in Objective-c.It will be better if you provide source code. If not, tell me which class is useful is good enough.
Finally i found a way to judge,may not the best way,but useful :
NSURL *url = [NSURL URLWithString:urlStr];
NSURL *lazyUrlStr = [NSURL URLWithString:[NSString stringWithFormat:#"http://%#",urlStr]];
if([[UIApplication sharedApplication] canOpenURL:url]){
NSLog(#"it's a url");
}else if([[UIApplication sharedApplication] canOpenURL:lazyUrlStr]){
NSLog(#"it's a url");
}else{NSLog(#"it isn't a url");
}
FYI: urlStr is the NSString to be judged

You can use URLWithString method of NSURL (if you are asking for NSString, not UIString):
NSURL *url = [NSURL URLWithString:yourUrlString];
if (url && url.scheme && url.host)
{
//the url is ok
NSLog(#"URL:%#", yourUrlString);
}
Hope this will help:)

Related

URLWithString return null

My code must update web view and download web site. But it doesn't because URLWithString returns null. How can I solve this problem? stringByAddingPercentEscapesUsingEncoding is already deprecated.
-(void) setWebViewMain:(NSString *) link {
// link = #"http://www.rbc.ru/society/05/09/2017/59ae2dfe9a794753f05e3e06"; if this string uncomment code is working
NSURL *url = [NSURL URLWithString: link];
NSLog(#"%#",url); // here url is (null)
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:requestObj];
[self.webView reload];
}
try as
-(void) setWebViewMain:(NSString *) link {
// link = #"http://www.rbc.ru/society/05/09/2017/59ae2dfe9a794753f05e3e06"; if this string uncomment code is working
NSURL *url = [NSURL URLWithString: [NSString stringWithFormat:#"%#",link]];
NSLog(#"%#",url); // here url is (null)
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:requestObj];
// [self.webView reload];
}
Just remove the last line from your method and it will work:
-(void) setWebViewMain:(NSString *) link {
// link = #"http://www.rbc.ru/society/05/09/2017/59ae2dfe9a794753f05e3e06"; if this string uncomment code is working
NSURL *url = [NSURL URLWithString: link];
NSLog(#"%#",url); // here url is (null)
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:requestObj];
//[self.webView reload];
}
You can call it like this:
[self setWebViewMain:#"http://www.rbc.ru/society/05/09/2017/59ae2dfe9a794753f05e3e06"];

load data from cache with NSURL doesn't work

i'm trying to load a photo from my cache directory.
this is the code where i write the photo into a cache folder:
+(BOOL)writeAData:(NSData *)imageData atURL:(NSURL *)fileUrl
{
return [imageData writeToURL:fileUrl atomically:YES];
}
this code works fine, but i have problems when i try to load the code from the cache folders:
i use the method initWithContentsOfURL inside a block:
NSData *imageData = [[NSData alloc] initWithContentsOfURL:self.imageUrl];
this is the format of url
file://localhost/Users/MarcoMignano/Library/Application%20Support/iPhone%20Simulator/6.1/Applications/0E8E54D8-9634-41CF-934B-A7315411F12F/Library/Caches/image_cache/Meyer%20Library.jpg
the URL is correct, but when i try to use the method above i get this error:
..... [__NSCFString isFileURL]: unrecognized selector sent to instance 0x8a0c5b0 .....
that is the code when i take the url of my model:
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:YES];
self.photos = [PhotoAlreadyDisplayed getAllPicture];
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([sender isKindOfClass:[UITableViewCell class]]) {
NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
if (indexPath) {
if ([segue.identifier isEqualToString:#"Show Image"]) {
if ([segue.destinationViewController respondsToSelector:#selector(setImageUrl:)]) {
NSURL *url = [[self.photos objectAtIndex:indexPath.row] valueForKey:#"url"];
[segue.destinationViewController performSelector:#selector(setImageUrl:) withObject:url];
[segue.destinationViewController setTitle:[self titleForRow:indexPath.row]];
}
}
}
}
}
whats wrong with the URL? how can i fix it? thank you
i have find the solution:
when i load the url for the model, i need to initialize the url using fileURLWithPath method:
NSURL *url = [NSURL fileURLWithPath:[[self.photos objectAtIndex:indexPath.row] valueForKey:#"url"]];
Now all works fine, thank you so much for yours help
[NSData initWithContentsOfURL:] is expecting an NSURL as the argument passed in. It looks like you might be passing in a string, rather than an NSURL. Is this the case?
EDIT: Just humour me - try replacing
NSData *imageData = [[NSData alloc] initWithContentsOfURL:self.imageUrl];
with
NSData *imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:self.imageUrl]];
What happens?
Though it doesn't look like you're returning successfully from initWithContentsOfURL:, but the snippet below may be of use to others:
NSError *error;
NSData *data = [[NSData alloc] initWithContentsOfURL:TestURL options:0 error:&error];
if(data) {
NSLog(#"Success");
}
else {
NSLog(#"Failed: %#", Error);
}
solution: when i load the url for the model, i need to initialize the url using fileURLWithPath method:
NSURL *url = [NSURL fileURLWithPath:[[self.photos objectAtIndex:indexPath.row] valueForKey:#"url"]];
Now all works fine, thank you so much for yours help

iOS: Show PDF in WebView

I´m trying to show a pdf in a webview, but the webview is always white / blank.
if i log the path from the local file, it can be logged, so the file is there..
Here is my code:
NSString *path = [[NSBundle mainBundle] pathForResource:#"fileName" ofType:#"pdf"];
NSURL *targetURL = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[webView loadRequest:request];
(webView is an iboutlet)
Maik
Please make sure the User Interaction Enabled & Multiple Touch are enabled.
Your targetURL is maybe nil, please debug this.
If the targetUrl is nil, this is maybe the 'path' has space.
So you should encode the path:
//Encode Url
+(NSString *) urlEncodeString:(NSString *) str
{
return [str stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
}
Controlling the whole characters rather than not just the space is more appropriate.Try this one for encoding the path of a file.
-(NSString *)urlenc:(NSString *)val{
CFStringRef safeString =
CFURLCreateStringByAddingPercentEscapes(NULL,
(CFStringRef)val,
NULL,
CFSTR("/%&=?$#+-~#<>|*,.()[]{}^!şığüöçĞÜŞİÖÇ"),
kCFStringEncodingUTF8);
return [NSString stringWithFormat:#"%#", safeString];
}

UIWebView doesn't load content

I don't understand why if I load the content of a UIWebView in XCode this way:
NSString *string = #"http://www.dummyurl.org/dummy.pdf";
NSURL *url = [NSURL URLWithString:string];
[my_view loadRequest:[NSURLRequest requestWithURL:url]];
everything works fine, but if a build the original string from a php script I wrote:
NSString *strURL = [NSSTring stringWithFormat:#"www.myserver.php"];
NSString *string = [[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:strURL]];
NSURL *url = [NSURL URLWithString:string];
[my_view loadRequest:[NSURLRequest requestWithURL:url]];
nothing works. I checked my script and it returns EXACTLY the original string (http://www.dummyurl.org/dummy.pdf) that works fine with the first method.
I build from a PHP script the content of a UITextView too, but that works fine.
I don't understand why this method works with the UITextView but not with the UIWebView to load the .pdf.
It may be useful
NSCharacterSet *characterSet = [NSCharacterSet whitespaceAndNewlineCharacterSet];
NSString *tempString = [string stringByTrimmingCharactersInSet:characterSet];
NSURL *url = [NSURL URLWithString:string];
[my_view loadRequest:[NSURLRequest requestWithURL:url]];
Make sure you linked the webview (IBOutlet) and the delegate.
With this lines it should load a url:
webView.delegate = self;
NSURLRequest *urlRequest;
NSString *urlToOpen = [NSString stringWithFormat:#"http://www.stackoverflow.com"];
urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:urlToOpen]];
[self.webView loadRequest:urlRequest];
Hope this helps...
I had this and it was a cache problem:
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0]];

not able to open a url with openURL in [UIApplication sharedApplication]?

i am trying to open a url
(http://c22.smaato.net/oapi/lp.jsp;jsessionid=E253E547A55290CA553F493659433DBF.c22)
on a button through the following code
NSString *strs=[[NSString alloc]initWithFormat:#"%#",[linkArry objectAtIndex:0]];
NSURL *urls = [NSURL URLWithString:strs];
[[UIApplication sharedApplication] openURL:urls];
[linkArry objectAtIndex:0] is the link mentioned above.
but it is not responding?? if i type something like "http://www.google.com" it works..
is there any other method to open these urls??
Check the line
NSURL *urls = [NSURL URLWithString:strs];
NSlog("urls : %#", urls);
and print the urls in console , if you find urls is nil,
then escape the strs with NSUTF8StringEncoding.
strs = [strs stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *urls = [NSURL URLWithString:strs];
Make sure that url is of NSURL type and not NSString