Implementing 'Download to Computer' functionality of browser - html

I am trying to download a mp3 file at a given link using NSURLConnection. However, I usually get time-out errors. Entering the link into the browser shows the default player, however the music file is not loaded either:
However, if I create the following simple HTML file:
<html>
<body>
Download
</body>
</html>
And then load the file into Safari, right click on the Download link, then select Download to Computer (or whathever it's called in English), Safari downloads the file.
Any ideas on how I can implement this in my own app?
I tried using
NSData *data = [NSData dataWithContentsOfURL:url];
and
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *r, NSData *data, NSError *e) { /.../ }];`
without success.

Seems like you're trying to hit a fly with a sledgehammer, using "NSURLConnection".
Try doing something a wee bit more high level such as
NSData * mp3data = [[NSData alloc] initWithContentsOfURL:options:error: ];
(the added benefit here is that you can get useful errors back via the "error:" parameter you pass into the method.

Here's an example on what you need to do:
NSURL* url = [NSURL URLWithString:yourMp3URLString];
//URL of the mp3 file
NSString* fileName = [NSString stringWithFormat:#"%#.mp3", mp3Name];
//NSString with the name of the mp3
NSString* destinationPath = [filePathString stringByAppendingPathComponent:fileName];
//NSString with the filePathString (NSString with path destination, you could
//change it to something like this #"User/Desktop")
//and add the NSString filename to the end of it
//so, if we have like User/Desktop it will become User/Desktop/mp3Name.mp3
NSURLRequest* request = [NSURLRequest requestWithURL:url];
NSURLDownload* download = [[NSURLDownload alloc] initWithRequest:request delegate:self];
[download setDestination:destinationPath allowOverwrite:NO];
//create the URLRequest and Download the mp3 to the destinationPath

Related

Display a preview of the website

I need to display a preview of the website with given url in the single image(e.g. like Facebook do in Messenger when you sending a url to someone). Is there any way to achieve that without actually loading the html file and reading it's metadata?
Try this,
NSString *urlStr = #"http://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a";
NSURL *url=[NSURL URLWithString: urlStr];
NSData *data=[NSData dataWithContentsOfURL:url];
UIImage *image=[[UIImage alloc] initWithData:data];
UIImageView *imagview = [[UIImageView alloc]initWithImage:image];
imagview.frame = CGRectMake(250, 500, 100, 100);
[self.view addSubview:imagview];
This will give just thumb or image.
You can use URLEmbeddedView Library for more functionality. I think this is the library what you want.

how to replace loading image from html img src on loading it from local file

I have HTML code. I want to preload images from it and save in local file. I transform HTML to NSAttributedString and show that string in UITextView.
NSAttributedString *htmlAttributedText =
[[NSAttributedString alloc] initWithData:[htmlText dataUsingEncoding:NSUTF16StringEncoding]
options:#{ NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType }
documentAttributes:nil
error:&err];
textView.attributedText = htmlAttributedText;
How to load images from local file instead of loading from internet?
Below code will list an array of images in your HTML. Get the list of all images
NSMutableArray * arrayToStoreImages = [[NSMutableArray alloc] init];
NSRegularExpression* imageRegex = [[NSRegularExpression alloc] initWithPattern:#"<img[^>]*>" options:0 error:NULL] ;
[imageRegex enumerateMatchesInString:HTMLBODY options:0 range:NSMakeRange(0, [HTMLBODY length]) usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop){
[arrayToStoreImages
addObject:NSStringFromRange(match.range)];
}];
Download all images using SDWebImage and store to local storage with name using HASH from fetched URL.
Replace the actual URL to local HASHed path.
Convert HTML to NSAttributedString and delete the image from local storage as it was temp.
If images is cached by SDWebImage it will be delivered from cache else it will download fresh one.
If i understand you right, as for me simplest and fastest way to use SDWebImage
after you once downloaded you image, lib save it and next time when you try to download image from the same url lib will give you cached image.

Loading local html from an array in xcode

I am attempting to load a locally hosted html file into a webview from an array. it looks something like this
_siteAddresses = [[NSArray alloc]
initWithObjects:#"file://localhost/var/mobile/Application/${APP_ID}/First Pentecostal Seminary.app/First_Pentecostal_Seminary/Main.html",...
with the corresponding code being
NSString *urlString = [_siteAddresses
objectAtIndex:indexPath.row];
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
self.detailViewController.webView.scalesPageToFit = YES;
[self.detailViewController.webView loadRequest:request];
What am I doing wrong...is it my coding or perhaps the html coding (I believe there may be some java in there)
Two thoughts:
That example file URL doesn't look right. How did you construct that? If it was something from your bundle on your device, I'd expect something more like:
file:///var/mobile/Applications/9E670C3C-C8B1-4B09-AE66-B43F7DB29F4D/First Pentecostal Seminary.app/...
Obviously, you have to programmatically determine this URL by using NSBundle instance method URLForResource or by using the bundle's bundleURL and then adding the appropriate path components.
You should (a) specify the view controller to be the delegate for your web view; and then (b) implement webView:didFailLoadWithError: and look at the error there, and it will inform you what the error was, if any.
For example, I have a file, test.html sitting in my bundle, which I can load into a web view like so:
NSURL *bundleURL = [[NSBundle mainBundle] bundleURL];
NSURL *url = [bundleURL URLByAppendingPathComponent:#"test.html"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];
I have set up my view controller as the delegate for the web view and have the following didFailLoadWithError:
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
NSLog(#"%s: %#", __FUNCTION__, error);
}
So, when I tried to load a request with an invalid URL this time (test2.html, which I do not have in my bundle), I get the following error:
2014-02-26 23:35:43.593 MyApp[3531:70b] -[ViewController webView:didFailLoadWithError:]: Error Domain=NSURLErrorDomain Code=-1100 "The requested URL was not found on this server." UserInfo=0x8c32f40 {NSErrorFailingURLStringKey=file:///Users/user/Library/Application%20Support/iPhone%20Simulator/7.0.3/Applications/FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF/MyApp.app/test2.html, NSErrorFailingURLKey=file:///Users/user/Library/Application%20Support/iPhone%20Simulator/7.0.3/Applications/FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF/MyApp.app/test2.html, NSLocalizedDescription=The requested URL was not found on this server., NSUnderlyingError=0x10424c90 "The requested URL was not found on this server."}
Try this code
UIWebView *documentsWebView=[[UIWebView alloc]init];
documentsWebView.delegate=self;
documentsWebView.frame=CGRectMake(0, 0, 1024, 616);
documentsWebView.backgroundColor=[UIColor clearColor];
[self.view addSubview:documentsWebView];
NSString* htmlString = [NSString stringWithContentsOfFile:[_siteAddresses
objectAtIndex:indexPath.row] encoding:NSUTF8StringEncoding error:nil];
[documentsWebView loadHTMLString:htmlString baseURL:nil];

How would you create a new local HTML file into a UIWebView on iOS?

First I would like to point out I'm very new to web development and more comfortable with iOS development, so excuse me if there's something fundamental I'm not understanding.
I've seen how you can place an HTML file into your apps directory and load it into a web view (Example). This is great, but how can you create a new local HTML file within the app? Such that the user can create a new html file to type in, and then store it (basic document style app functionality). Perhaps with some sort of Javascript (I'm not too familiar with such Javascript)?
You can build the HTML in a NSString like so:
// get user input
NSString *userText = #"Hello, world!";
// build the HTML
NSString *html = [NSString stringWithFormat:#"<html><body>%#</body><html>", userText];
// build the path where you're going to save the HTML
NSString *docsFolder = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *filename = [docsFolder stringByAppendingPathComponent:#"sample.html"];
// save the NSString that contains the HTML to a file
NSError *error;
[html writeToFile:filename atomically:NO encoding:NSUTF8StringEncoding error:&error];
Clearly I'm just setting the userText to some literal, but you could obviously let the user type it into a UITextView and grab it from there.
You can then load the HTML into a web view with:
[self.webView loadHTMLString:html baseURL:nil];
or with:
NSURL *url = [NSURL fileURLWithPath:filename];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];

Injecting local files into UIWebView without breaking links

I am working on an iOS app that needs to display webpages from a server inside a UIWebView while injecting relevant local png and css files as needed in order to speed up load time. Here is the code I am using to try to do this:
NSData *myFileData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://www.example.com/index.html"]]];
NSString* myFileHtml = [[NSString alloc] initWithData:myFileData encoding:NSASCIIStringEncoding];
[myWebView loadHTMLString:myFileHtml baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];
My problem is that some of the webpages have buttons in them that link to other webpages on the server, and because the UIWebView is only loading a string, the buttons when tapped don't cause the UIWebView to load the new webpage URL like it would if I had used the loadRequest method.
My question is how can I get the the UIWebView to behave like it is loading a request while still injecting local files from the baseurl?
Thanks
The relative links in the button cannot work, because the linked pages are on a remote server and not on the device's file system. However you can use a UIWebViewDelegate method to make it work:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
if (navigationType == UIWebViewNavigationTypeLinkClicked) {
NSString *localRootPath = [NSString stringWithFormat:#"file://%#", [[NSBundle mainBundle] bundlePath]];
NSString *remoteRootPath = #"http://yourdomain.com";
NSString *remotePath = [[request.URL absoluteString] stringByReplacingOccurrencesOfString:localRootPath withString:remoteRootPath];
[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:remotePath]]];
// or you can use your own loading mechanism here
return NO;
}
return YES;
}
This method intercepts all requests from your WebView. If the request was triggered by a user tap / click the URL gets modified from a relative URL to a absolute URL so it can be loaded from the server. Don't forget to set the delegate on the WebView or this method will not be called.
NSURLPRotocol is a handler for NSURLConnection and will give you the opportunity to intercept the calls to the server and substitute your own content.
1) Derive a class from NSURlProtocol
2) Call NSURLProtocol registerClass: in your application:didFinishLaunchingWithOption
3) Read the documentation on implement these methods as necessary:
initWithRequest:cachedResponse:client:,
startLoading,
URLProtocol:didReceiveResponse:cacheStoragePolicy:
URLProtocolDidFinishLoading: