I have a problem when downloading a file. I have a zip file that has 90 MB and it is filling my RAM memory to hudge amounts until the file is downloaded. Could somene help me with some example code that shows any better way to do this and not overload my RAM?
Thanks.
Code:
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSURL *url = [NSURL URLWithString:#"http://autoskola.1e29g6m.xip.io/mobileData/slike3.zip"];
NSError *error = nil;
NSData *data = [NSData dataWithContentsOfURL:url options:0 error:&error];
if(!error){
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
NSString *zipPath = [path stringByAppendingPathComponent:#"slike3.zip"];
[data writeToFile:zipPath options:0 error:&error];
if(!error){
//unziping the files
ZipArchive *za = [[ZipArchive alloc] init];
if([za UnzipOpenFile:zipPath]){
BOOL ret = [za UnzipFileTo:path overWrite:YES];
if(NO == ret){} [za UnzipCloseFile];
}
}else{
NSLog(#"Error saving file %#", error);
}
}else{
NSLog(#"Error downloading zip file: %#", error);
}
});
You may want to consider looking into AFNetworking. It's probably the most commonly used library for accessing the internet. You can use it to download a file and take the output stream and write the data into a file. This will allow you to download and write the file as chunks of data instead of all at once. You'll want to take a look at the AFNetworking Docs for information on downloading the file. You'll also want to look into the docs for NSFileHandle for information on how to write data into a file.
Related
I'm new to encryption and am trying to encrypt recordings with RNCryptor. The files are encrypted properly but, after decrypting, the created NSData causes the AVAudioPlayer to fail initialization. The method I'm using for the encryption and decryption are...
- (void)renameFileInDocumentsFolder:(NSString *)oldFilename withNewName:(NSString *)newFilename
{
NSFileManager *filemgr;
NSString *oldPath = [self getFilePathFromDocumentsFolder:oldFilename];
filemgr = [NSFileManager defaultManager];
NSData *data = [filemgr contentsAtPath:oldPath];
NSString *destPath = [[oldPath stringByDeletingLastPathComponent] stringByAppendingPathComponent:[newFilename stringByAppendingString:#".m4a"]];
NSLog(#"DEST:%#", destPath);
NSError *error;
NSData *encryptedData = [RNEncryptor encryptData:data
withSettings:kRNCryptorAES256Settings
password:#"ABC123"
error:&error];
[encryptedData writeToFile:destPath atomically:YES];
[filemgr removeItemAtPath:oldPath error:&error];
}
-(NSData *)decryptFilePathFromDocumentsFolder:(NSString *)filename
{
AudioRecorderAppDelegate *appDelegate=[AudioRecorderAppDelegate sharedDelegate];
_cacheDirectory = [[[appDelegate applicationCacheDirectory]path]stringByAppendingPathComponent:#"Recordings"];
// NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSString *filePath = [_cacheDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.m4a", filename]];
NSData *data = [NSData dataWithContentsOfFile:filePath];
NSData *decData = [RNDecryptor decryptData:data withPassword:#"ABC123" error:&error];
return decData;
}
The AVAudioPlayer initialization is...
- (void)initializeAudioPlayer
{
NSData *recording = [self decryptFilePathFromDocumentsFolder:_fileNameTextField.text];
if(!audioPlayer)
{
NSError *error=nil;
audioPlayer = [[AVAudioPlayer alloc]
initWithData:recording fileTypeHint:#".m4a" error:&error];
if (error)
NSLog(#"Error: %#", [error localizedDescription]);
else
I don't know what I'm doing wrong or if RNCryptor is even meant to encrypt audio files but any help would be greatly appreciated.
There are lots of places where you're not checking errors, both in the cryptor calls, and in the reading and writing of the file. Make sure at each point that you actually have what you expect. Make sure the written and returned data are of reasonable sizes (about the same as the original file). Make sure the original file actually is playable. Makes sure after decryption you have precisely the same bytes as you started with.
RNCryptor doesn't care what it encrypts. But if you're doing this on the UI thread (which it looks like you're doing, reading a large file from disk can cause you're program to hang, in some cases long enough for the OS to kill you. Generally large file operations (like large audio files) need to be done asynchronously.
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.
I am new iPhone developer.I am developing iPhone app in this app Google drive integration it is successfully.but I want to download jpg,png,pdf,doc.ppt,rtf,etc file are download.
all file and folder display in Table view.I want do download the selected file from the table view.so how can do this ?
I am read this link https://developers.google.com/drive/v2/reference/files/get but i can not understand.here how to call all this function.
I want to download file's from Google Drive and save in document directory.
I am try this code.
NSString *downloadedString = file.downloadUrl; // file is GTLDriveFile
NSLog(#"%#",file.downloadUrl);
GTMHTTPFetcher *fetcher = [self.driveService.fetcherService fetcherWithURLString:downloadedString];
[fetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *error)
{
if (error == nil)
{
if(data != nil)
{
GTLDriveFile *file = [driveFiles objectAtIndex:indexPath.row];
NSString *filename=file.title;
//this variable globalObj.documentPath is global variable for document directory path.
filename = [globalObj.documentPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#",filename]];
filename=[filename stringByReplacingOccurrencesOfString:#"file:/private" withString:#"file:///"];
NSLog(#"File name : %#",filename);
NSURL *targetURL=[[NSURL alloc] initFileURLWithPath:downloadedString];
NSData* Data = [[NSData alloc]initWithContentsOfURL:targetURL];
[Data writeToFile:filename atomically:YES];
NSLog(#"my path:%#",filename);
}
}
else
{
NSLog(#"Error - %#", error.description);
}
}];
so places help me.I want to download file and save in document directory.
any link for code places suggestion me.
Thanks
you does not have to do all this stuff.
here is just simple code
image url is from dropbox.
NSString *stringURL = #"https://dl.dropboxusercontent.com/s/pquhnr5pt37uk6q/backkk.jpeg?dl=1&token_hash=AAEXBejAXoD__RPMBom6nL2F5_Uhu62ed0puhtLIt2FGug";
NSURL *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,#"yourfile.png"];
[urlData writeToFile:filePath atomically:YES];
}
and finally you can represent it any way you want.
If you want to download large data.then use Threading concept.
if you use imageview programetically then write below code..... myimg=[[UIImageView alloc]initWithFrame:CGRectMake(30, 100, 100, 100)];
myimg.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:#"https://dl.dropboxusercontent.com/s/pquhnr5pt37uk6q/backkk.jpeg?dl=1&token_hash=AAEXBejAXoD__RPMBom6nL2F5_Uhu62ed0puhtLIt2FGug"]]];
[self.view
addSubview:myimg]; it's working
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"
)
I am using multipeer connectivity in my application. The user can send any file, such as a png or a recording to another peer. Since the transfer was slow I thought that zipping the data in a zip would speed it up as the size is reduced. I decided to use a framework for this suggested in the second answer to this question:
How can I create a zip file by using Objective C?
The problem is that I need to provide the usl of the file to send it via bluetooth, and I tried doing it in this way:
NSData *file = [NSData dataWithContentsOfURL:imageUrl];
ZipFile *zipFile= [[ZipFile alloc] initWithFileName:#"file.zip" mode:ZipFileModeCreate];
ZipWriteStream *stream= [zipFile writeFileInZipWithName:#"abc.txt" compressionLevel:ZipCompressionLevelBest];
[stream writeData:file];
[stream finishedWriting];
NSString *docsDir;
NSArray *dirPaths;
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
NSString *databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent:#"file.zip"]];
[stream writeToFile:databasePath atomically:YES];
_progressSend = [session sendResourceAtURL: WHAT URL?? withName: info toPeer:peerID withCompletionHandler:^(NSError *error) {
// Implement this block to know when the sending resource transfer completes and if there is an error.
if (error) {
NSLog(#"Send resource to peer [%#] completed with Error [%#]", peerID.displayName, error);
}
else {
// Create an image transcript for this received image resource
}
}];
The problem is that I don't get how to get the url of the zip. I can't even save it in the documents directory...