Caching and saving videos in tableview - objective-c

I'm displaying videos with tableview and would like to save urls/data in cache so user won't have to download the same video again when replayed.
However I'd like to keep them only until user quits the app. The next time he opens the app he'll have to download them again so I only need to save them for the app's active lifetime.
Should I still do caching or is there a more efficient way to do this?
-(void)loadVideo:(NSString *)urlString {
NSURL *url = [NSURL URLWithString:urlString];
NSString* cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* file = [cachePath stringByAppendingPathComponent:#"/EGOCache.plist"];
NSDictionary *dict =[NSDictionary dictionaryWithContentsOfFile:file];
if ([dict objectForKey:urlString] )
{
NSData *data = [[EGOCache globalCache] dataForKey:urlString];
data = [NSURLConnection sendSynchronousRequest:
[NSURLRequest requestWithURL:url]
returningResponse:nil
error:nil];
NSLog(#"loading from cache %#",urlString);
}else{
NSData *data = [NSURLConnection sendSynchronousRequest:
[NSURLRequest requestWithURL:url]
returningResponse:nil
error:nil];
[[EGOCache globalCache] setData:data forKey:urlString];
NSLog(#"saving cache %#",urlString);
}
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval: 10.0];
[self.videoPlayer setContentURL:[request URL]];}

AVFoundation allows for streaming a video file on disk.
I suggest you look into saving the video in the Documents folder or Caches folder and steam it to AVFoundation from there. Then when the user quits the app, applicationWillTerminate gets called and you can wipe the videos from disk.
EDIT
Using MPMoviePlayerController:
MPMoviePlayerController *player = [[MPMoviePlayerController alloc] initWithContentURL: URL-TO-FILE-ON-DISK];
[player prepareToPlay];
[player.view setFrame: myView.bounds]; // player's frame must match parent's
[myView addSubview: player.view];
// ...
[player play];

Related

how to load pdf in binary format on UIWebview iOS?

I want to open a pdf file when user clicks on download button, but the data loaded is decode, how can i convert response data to be as a pdf file? i am not loading it from local document or bundle.
NSMutableURLRequest *requestObj = [NSMutableURLRequest requestWithURL:url];
[webViewForDocsView loadRequest:requestObj];
[self.view addSubview:webViewForDocsView];
To load raw data first create a NSData object with the content of the url response, then load the data by specifying the mime type and data, like the code snippet:
NSURL *url = [[NSURL alloc] initWithString:#"binary file link"];
NSError *error;
/**
* GET the data from a url link
*/
NSData *data = [NSData dataWithContentsOfURL:url
options:NSDataReadingUncached
error:&error];
if (error) { // validation
NSLog(#"data error: %#", error);
}
UIWebView *webView = [[UIWebView alloc] initWithFrame:self.view.frame];
[self.view addSubview:webView];
/**
* Load the request fro mthe binaray data
*/
[webView loadData:data
MIMEType:#"application/pdf"
textEncodingName:#"utf-8"
baseURL:[NSURL URLWithString:#"http://example.com/"]];

Using AFNetworking to download a pdf from the web in appdelegate and then trying to load that stored pdf in a UIWebview on another page

I am using AFNetworking to download a pdf (that will change on a weekly basis) and save it into the documents directory with this code:
//Get the PDF
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.somewebsiteaddress/CurrentEdition1.pdf"]];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"CurrentEdition1.pdf"];
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:filePath append:NO];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Successfully downloaded file to %#", filePath);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
[operation start];
I then want to read that saved file in another section of the app in a UIWebView (after it has downloaded) and use this code:
//Now create Request for the file that was saved in your documents folder
NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:#"Documents"]];
NSString *filePath = [resourceDocPath stringByAppendingPathComponent:#"CurrentEdition1.pdf"];
NSURL *url = [NSURL fileURLWithPath:filePath];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[webVieweedition setUserInteractionEnabled:YES];
[webVieweedition setDelegate:self];
[webVieweedition loadRequest:requestObj];
I have used a few single page pdf documents to test with - loading them up on the server and then seeing if they are downloaded and then viewed when changed. Problem is, this seems to only be working about 50% of the time. I'll put a new file up and sometimes the correct one will be shown in the UIWebView and sometimes it will show the previous one and not the new one. I am waiting until I see the download completed message before I try to go to the UIWebView (although I know clients won't do that, but that's a whole other question). Anyway, I'm new to XCode and have just been a web html guy. This has had my head spinning for two days. Using Storyboards, ARC, XCode 4.6.2.
If i understood right, sometimes you see the same pdfs in app, although you changed them on webserver?May be the reason is cache, try construct request this way, ignoring caching
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://www.somewebsiteaddress/CurrentEdition1.pdf"] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10];

How to stop UIWebView loading immediately

As ios documentation says, [webView stopLoading] method should be used in order to stop webview load task.
As far as I see, this methods runs asynchronously, and does NOT stop currently processing load request immediately.
However, I need a method which will force webview to immediately stop ongoing task, because loading part blocks the main thread, which could result in flicks on animations.
So, is there a way to succeed this?
This worked for me.
if (webText && webText.loading){
[webText stopLoading];
}
webText.delegate=nil;
NSURL *url = [NSURL URLWithString:#""];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[webText loadRequest:requestObj];
Don't use the UIWebView to download your html document directly.
Use async download mechanism like ASIHTTPRequest to get your html downloaded by a background thread.
When you get the requestFinished with a content of your html then give it to the UIWebView.
Example from the ASIHTTPRequest's page how to create an asynchronous request:
- (IBAction)grabURLInBackground:(id)sender
{
NSURL *url = [NSURL URLWithString:#"http://allseeing-i.com"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
[request startAsynchronous];
} 
- (void)requestFinished:(ASIHTTPRequest *)request
{
// Use when fetching text data
NSString *responseString = [request responseString];
 
// Use when fetching binary data
NSData *responseData = [request responseData];
}  
- (void)requestFailed:(ASIHTTPRequest *)request
{
NSError *error = [request error];
}
Use the responseString to your UIWebView's loadHTMLString method's parameter:
UIWebView *webView = [[UIWebView alloc] init];
[webView loadHTMLString:responseString baseURL:[NSURL URLWithString:#"Your original URL string"]];

How to store a pdf file loaded into an UIWebView in my Documents directory?

Currently, I detect if the UIWebView load a pdf file by doing a check on the current URL. Next I download the pdf file with ASIHTTPRequest library. The problem is that if the file is display in the UIWebView, is that it is already downloaded somewhere, so I download this file twice. How can I get this file load in my UIWebView ?
The purpose is to store this file loaded in my UIWebView in my Document directory.
Here's how you can download, read and store your pdf locally in iphone application, so that you don't have to download regularly:
First create UIWebView and include <<UIWebViewDelegate>>
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *filePath = [documentsPath stringByAppendingPathComponent:#"YourPDF.pdf"];
if(![[NSFileManager defaultManager] fileExistsAtPath:filePath]){ // if file not present
// download file , here "https://s3.amazonaws.com/hgjgj.pdf" = pdf downloading link
NSData *pdfData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:#"https://s3.amazonaws.com/hgjgj.pdf"]];
//Store the downloaded file in documents directory as a NSData format
[pdfData writeToFile:filePath atomically:YES];
}
NSURL *url = [NSURL fileURLWithPath:filePath];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[yourWebView setUserInteractionEnabled:YES];
[yourWebView setDelegate:self];
yourWebView.scalesPageToFit = YES;
[yourWebView loadRequest:requestObj];
Or, if you simply want to read/load pdf from your Resource folder then simply do this :
NSString* filePath= [[NSBundle mainBundle] pathForResource:#"sample" ofType:#"pdf"]];
/// or you can even read docs file as : pathForResource:#"sample" ofType:#"docx"]
NSURL *url = [NSURL fileURLWithPath:filePath];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[yourWebView setUserInteractionEnabled:YES];
[yourWebView setDelegate:self];
yourWebView.scalesPageToFit = YES;
[yourWebView loadRequest:requestObj];
All I can suggest is either to download it a second time, or put it in the temporal storage and then put it it the UIWebView and when the user asks, then put it where you want from the temporal storage.

Audio playback does not start

NSError *err;
// Initialize audio player
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&err];
audioPlayer.delegate = self;
[audioPlayer play];
With the code above, I'm trying to initialize playback of a .mp3 file, however the playback does not start at all. There is no sound. What am I doing wrong? I have inspected 'err' and there is nothing there.
Edit: After adding AVAudioSession, I'm getting the following error from AVAudioPlayer
The operation couldn’t be completed. (OSStatus error -43.)
Apparently AVAudioPlayer does not support streaming via. HTTP as I was trying to do, so by using AVPlayer instead, I got it working.
Did you initialize a AVAudioSession?
The following works fine for me. Might give you a hint of whats not working for you.
Initializing:
AVAudioSession* session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryAmbient error:nil];
[session setActive:TRUE error:nil];
Loading:
AVAudioPlayer* audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileUrl error:nil];
audioPlayer.numberOfLoops = 0;
[audioPlayer prepareToPlay];
audioPlayer.volume = 1.0;
Playing:
[audioPlayer play];
Update
To find the right NSRUL for fileUrl, I used this code:
NSURL* fileUrl = [NSURL fileURLWithPath:
[[NSBundle mainBundle] pathForResource:#"MySound" ofType:#"wav"] isDirectory:NO];
And then I added MySound.wav to the project (bundle).