Download folder from server to local iPad / iPhone - ios

I want to create an application that automatically downloads a folder from my own server and store it locally on the iPad/iPhone. How can i accomplish this and where does the folder get stored on the local iDevice ? Therefore how will i access it afterwards? Many thanks for your help

The best way to do so was actually putting all the pictures for example in one zip file, downloading it and unzipping it on the real device using this code :
dispatch_queue_t queue = dispatch_get_global_queue(
DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSURL *url = [NSURL URLWithString:#"someDirectory/newPics.zip"];
NSError *error = nil;
// 2
NSData *data = [NSData dataWithContentsOfURL:url options:0 error:&error];
if(!error)
{
// 3
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
NSString *zipPath = [path stringByAppendingPathComponent:#"newPics.zip"];
[data writeToFile:zipPath options:0 error:&error];
if(!error)
{
ZipArchive *za = [[ZipArchive alloc] init];
// 1
if ([za UnzipOpenFile: zipPath]) {
// 2
BOOL ret = [za UnzipFileTo: path overWrite: YES];
if (NO == ret){} [za UnzipCloseFile];
// 3
NSString *imageFilePath = [path stringByAppendingPathComponent:#"newPics/pic1.png"];
//[self removeImage:zipPath];
[[NSFileManager defaultManager] removeItemAtPath:zipPath error: &error];
dispatch_async(dispatch_get_main_queue(), ^{
NSURL *fileURL = [NSURL fileURLWithPath:imageFilePath];
[_webV loadRequest:[NSURLRequest requestWithURL:fileURL]];
});
}
}
else
{
NSLog(#"Error saving file %#",error);
}
}
else
{
NSLog(#"Error downloading zip file: %#", error);
}
});
It's the best way to do it , fast and reliable.

Related

I'm unable to save or download video in document directory and play from document directory

I want to download or save youtube video in document directory and then play that video using MPMoviePlayerViewController. But I don't know why my code is not working.
I'm using this below code :
prgrma mark- download Or save
-(IBAction)onclick_download:(id)sender
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSLog(#"Downloading Started");
NSString *urlToDownload = #"youtubeurl";
NSURL *url = [NSURL URLWithString:urlToDownload];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,#"thefile.mp4"];
//saving is done on main thread
dispatch_async(dispatch_get_main_queue(), ^{
[urlData writeToFile:filePath atomically:YES];
NSLog(#"File Saved !");
});
}
});
}
pragma mark- Play video from document directory
-(IBAction)onclick_playvideolocally:(id)sender
{
[self playvideolocally];
}
-(void)playvideolocally
{
NSURL *videoUrl;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray *filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory error:nil];
NSLog(#"files array %#", filePathsArray);
NSString *fullpath;
for ( NSString *apath in filePathsArray )
{
fullpath = [documentsDirectory stringByAppendingPathComponent:apath];
videoUrl =[NSURL fileURLWithPath:fullpath];
}
MPMoviePlayerViewController *videoPlayerView = [[MPMoviePlayerViewController alloc] initWithContentURL:videoUrl];
[self presentMoviePlayerViewControllerAnimated:videoPlayerView];
[videoPlayerView.moviePlayer play];
}
As your link you provided in url is for youtube so it is not downloaded or saved in local
Use this for youtube
Ive used classes from this project: https://github.com/larcus94/LBYouTubeView It works fine for me. I can download youtube videos.
LBYouTubeExtractor *extractor = [[[LBYouTubeExtractor alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:(#"http://www.youtube.com/watch?v=%#"), self.videoID ]] quality:LBYouTubeVideoQualityLarge] autorelease];
[extractor extractVideoURLWithCompletionBlock:^(NSURL *videoURL, NSError *error) {
if(!error) {
NSLog(#"Did extract video URL using completion block: %#", videoURL);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData *data = [NSData dataWithContentsOfURL: videoURL];
NSString *pathToDocs = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filename = [NSString stringWithFormat:(#"video_%#.mp4"), self.videoID ];
[data writeToFile:[pathTODocs stringByAppendingPathComponent:filename] atomically:YES];
NSLog(#"File %# successfully saved", filename);
});
} else {
NSLog(#"Failed extracting video URL using block due to error:%#", error);
}
}];

How can download audio? objective-c

I have audio player. I download audio in this way
- (void) song{
if (_index == 0) {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"1.mp3"];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:filePath isDirectory:NO];
if (!fileExists) {
NSString *stringURL = #"https://drive.google.com/uc?export=download&id=0B6zMam2kAK39VHZ1cUZsM3BhQXM";
NSURL *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
[urlData writeToFile:filePath atomically:YES];
}
self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL URLWithString:filePath] error:nil];
}
}
But when audio downloading I can’t do anything. User interface stop.
How can download audio and do anything in user interface simultaneously?
Give your method a block to execute when finished, then run the download code in the background. Lets say, for your case the output is a local file with the downloaded content:
- (void)songWithCompletion:(void (^)(NSString *))completion {
NSString *filePath = [self song];
dispatch_async(dispatch_get_main_queue(), ^{
if (completion) completion(filePath);
});
}
Change the song method to return filePath. Don't ever call it directly, only via songWithCompletion.
- (void)song {
// ... your code from the OP
// don't allocate the audio player here, just return the local file
return filePath;
}
Call it like this...
[self songWithCompletion:^(NSString *filePath) {
if (filePath) {
self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL URLWithString:filePath] error:nil];
// you should really handle audio player error here, too
} else {
// handle error
}
}];
You are downloading the file in the main thread. you need to make an asynchronous call in order to avoid stopping UI.
-(void)downloadAudio
{
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:#"https://drive.google.com/uc?export=download&id=0B6zMam2kAK39VHZ1cUZsM3BhQXM"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
receivedData = [NSMutableData data] ;
} else {NSLog(#"no connection!");
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSLog(#"Succeed! Received %d bytes of data",[receivedData length]);
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//NSLog(#"%#", [documentPaths objectAtIndex:0]);
NSString *documentDirectoryPath = [documentPaths objectAtIndex:0];
NSString *folderPath = [documentDirectoryPath stringByAppendingPathComponent:#"audioFile.mp3"];
[receivedData writeToFile:folderPath atomically:YES];
NSURL *soundURL = [NSURL fileURLWithPath:folderPath];
NSError *error;
if ([[NSFileManager defaultManager] fileExistsAtPath:folderPath]) {
player = [[AVAudioPlayer alloc]initWithContentsOfURL:soundURL error:&error];
player.volume=0.5;
NSError *error = nil;
if (!error) {
[player play];
NSLog(#"File is playing!");
}
else{
NSLog(#"Error in creating audio player:%#",[error description]);
}
}
else{
NSLog(#"File doesn't exist");
}
}

iOS zip file Unzipping code issue

I want to unzip a zip file downloaded from web but my issue is the zip file is not unzipping in if-else statement.
Is it wrong anything if it is then kindly guide me.
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSURL *url = [NSURL URLWithString:#"http://www.icodeblog.com/wp-content/uploads/2012/08/zipfile.zip"];
NSError *error = nil;
// 2
NSData *data = [NSData dataWithContentsOfURL:url options:0 error:&error];
if(!error)
{
// 3
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
NSString *zipPath = [path stringByAppendingPathComponent:#"zipfile.zip"];
[data writeToFile:zipPath options:0 error:&error];
if(!error)
{
// TODO: Unzip
ZipArchive *za = [[ZipArchive alloc] init];
// 1
if ([za UnzipOpenFile: zipPath]) {
// 2
BOOL ret = [za UnzipFileTo: path overWrite: YES];
if (NO == ret){} [za UnzipCloseFile];
// 3
NSString *imageFilePath = [path stringByAppendingPathComponent:#"photo.png"];
NSString *textFilePath = [path stringByAppendingPathComponent:#"text.txt"];
NSData *imageData = [NSData dataWithContentsOfFile:imageFilePath options:0 error:nil];
UIImage *img = [UIImage imageWithData:imageData];
NSString *textString = [NSString stringWithContentsOfFile:textFilePath
encoding:NSASCIIStringEncoding error:nil];
// 4
dispatch_async(dispatch_get_main_queue(),^{
self.imageView.image = img;
self.label.text = textString;
});
}
else
{
NSLog(#"Error saving file %#",error);
}
}
else
{
NSLog(#"Error downloading zip file: %#", error);
}
}
});
As per your code debugging
1) NSData *data = [NSData dataWithContentsOfURL:url options:0 error:&error];
data is "nil"
by adding in plist below lines of code
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key><true/>
</dict>
you will get expected output

How to unzip a downloaded data and use a particular file from the unzipped file (index.html) to load in a UIWebview

I am stuck with unziping a zip file and fetch a paritcular file from that unzipped content (index.html) and finally use that index.html to load a UIWebview .
Am using GZIP library to unzip the file which am downloading
[data gunzippedData];
Is the method which am using to unzip the data using GZIP .
For unzipping the file from web use the below code.
Dowbload ZipArchive.h and #import in your file.
NSURL *urlVersion = [NSURL URLWithString: [tempDirOuter objectForKey:#"filename"]];
NSLog(#"txt File : %#",urlVersion);
NSError *error = nil;
// 2
NSData *data = [NSData dataWithContentsOfURL:urlVersion options:0 error:&error];
NSString *textFilePath;
if(!error)
{
// 3
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
NSString *strFileName = [tempDirOuter objectForKey:#"fileNameOnly"];
NSString *zipPath = [path stringByAppendingPathComponent:strFileName];
[data writeToFile:zipPath options:0 error:&error];
ZipArchive *za = [[ZipArchive alloc] init];
// 1
if ([za UnzipOpenFile: zipPath])
{
// 2
BOOL ret = [za UnzipFileTo: path overWrite: YES];
if (NO == ret){} [za UnzipCloseFile];
// 3
NSString *StrName = [strFileName stringByReplacingOccurrencesOfString:#".zip" withString:#".txt"];
textFilePath = [path stringByAppendingPathComponent:StrName];
}
if(!error)
{
// TODO: Unzip
}
else
{
NSLog(#"Error saving file %#",error);
}
}
else
{
NSLog(#"Error downloading zip file: %#", error);
}
NSString *webVersion = [NSString stringWithContentsOfFile:textFilePath encoding:NSASCIIStringEncoding error:nil];
In string webVersion you will get the html path.

How to list unknown files when unzipping in iOS?

I've started using ZipArchive because I have a testing app that displays images from a server where the content is often changing. I want the app to sort and display the images, without having an explicit list of the new image names. (Or maybe I should also include in the zipped file an XML document that contains the names of the new images.) Either way, I'm now having a problem adding a known image to the zip file on the server and finding it in the app.
The original zipfile.zip file has 2 files: photo.png and text.txt
That works. So I downloaded the zipfile.zip and uploaded it to my server. It still worked, of course.
Then I unzipped it, added a new image to it, and re-zipped it on my server.
The updated zipfile.zip now has 3 files: photo.png, myphoto.png, and text.txt
The image I added, myphoto.png, can't be found. What am I missing?
- (void) viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSURL *url = [NSURL URLWithString:#"http://www.icodeblog.com/wp-content/uploads/2012/08/zipfile.zip"];
NSError *error = nil;
NSData *data = [NSData dataWithContentsOfURL:url options:0 error:&error];
if(!error) {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachePath = [paths objectAtIndex:0];
NSString *zipPath = [cachePath stringByAppendingPathComponent:#"zipfile.zip"];
[data writeToFile:zipPath options:0 error:&error];
if(!error) {
ZipArchive *za = [[ZipArchive alloc] init];
if ([za UnzipOpenFile: zipPath]) {
BOOL ret = [za UnzipFileTo: cachePath overWrite: YES];
if (NO == ret){
}
[za UnzipCloseFile];
// NSString *imageFilePath=[cachePath stringByAppendingPathComponent:#"photo.png"];
NSString *imageFilePath=[cachePath stringByAppendingPathComponent:#"myphoto.png"];
NSData *imageData = [NSData dataWithContentsOfFile:imageFilePath options:0 error:nil];
if (imageData) {
NSLog(#"found data");
} else {
NSLog(#"no data");
}
UIImage *img = [UIImage imageWithData:imageData];
NSString *textFilePath = [cachePath stringByAppendingPathComponent:#"text.txt"];
NSString *textString = [NSString stringWithContentsOfFile:textFilePath encoding:NSASCIIStringEncoding error:nil];
dispatch_async(dispatch_get_main_queue(), ^{
self.imageView.image = img;
self.label.text = textString;
});
}
} else {
NSLog(#"Error saving file %#",error);
}
} else {
NSLog(#"Error downloading zip file: %#", error);
}
});
}
When I run this, looking for the image I added, it returns "no data". Why? And the bigger question is: Can I, in my iOS app, list the contents of an unzipped file?
I started this project with this question which mention this code: SSZipArchive. It works well.
I've tested you code ... and is working fine for me...
The main change:
instead:
ZipArchive *za = [[ZipArchive alloc] init];
if ([za UnzipOpenFile: zipPath]) {
BOOL ret = [za UnzipFileTo: cachePath overWrite: YES];
if (NO == ret){
}
[za UnzipCloseFile];
I'm using
[SSZipArchive unzipFileAtPath:zipPath toDestination:cachePath];
You can list the content of a directory (after unzip):
NSArray * directoryContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:cachePath error:&error];
NSLog(#"DIR folder : %#",directoryContents);
You can check here my demo project based on your code https://dl.dropboxusercontent.com/u/19438780/testSSZipArchive.zip
UPDATE
testing with my zip file I have:
(
"__MACOSX",
"Archive.zip",
"error feedly.txt",
"image1.jpg",
"image2.jpg",
"image3.jpg",
"image4.jpg",
"Tony-M.testSSZipArchive"
)

Resources