How can I save multiple files from an NSData object? - iphone

So I have a zip file, which gets extracted using Objective-Zip. The extracted contents then get put into an NSData object. I want to save the contents into the apps Documents folder. The problem is these are multiple files, and writeToFile:atomically: saves the contents of the zip into one file.
Any ideas? The other question I saw just said to use ZipArchive.
I need help fast, because the app needs to be finished by the end of my work tomorrow.

I think you need to use ZipArchive:
ZipArchive* za = [[ZipArchive alloc] init];
NSData *Data = [NSData dataWithContentsOfURL:url]; // here url is your zip url
NSArray *documentPathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirString = [documentPathArray objectAtIndex:0];
NSString *filePath = [documentsDirString stringByAppendingPathComponent:#"temp.zip"];
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
NSError *writeError = nil;
[Data writeToURL: fileURL options:0 error:&writeError];
if( writeError) {
NSLog(#" Error in writing file %#' : \n %# ", filePath , writeError );
return;
}
if( [za UnzipOpenFile:filePath] )
{
BOOL ret = [za UnzipFileTo:documentsDirz overWrite:YES];
if( NO==ret )
{
NSLog(#"NO");
}
[za UnzipCloseFile];
}
for more info

Related

Can't get the path of the file

The code was working 100% but after shifting to iOS7 and XCode 5 I can't get the path of the file using NSFilemanager methods, the code can't find the path to timetableXML file and triggers -> else #"NO such a file exist", Here is there code:
- (void)viewDidLoad
{
[super viewDidLoad];
APUAppDelegate *appDelegate = (APUAppDelegate *)[[UIApplication sharedApplication]delegate];
context = [appDelegate managedObjectContext];
dispatch_queue_t queue = dispatch_get_global_queue(0,0);
dispatch_async(queue, ^{
NSLog(#"Beginning download");
NSString *stringURL = #"http://webspace.apiit.edu.my/intake-timetable/download_timetable/timetableXML.zip";
NSURL *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
NSLog(#"Got the data!");
//Find a cache directory. You could consider using documenets dir instead (depends on the data you are fetching)
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
//Save the data
NSLog(#"Saving");
dataPath = [path stringByAppendingPathComponent:#"timetableXML.zip"];
dataPath = [dataPath stringByStandardizingPath];
[urlData writeToFile:dataPath atomically:YES];
/////////////////// TEST
// Existence of the xml file
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *pathToMyFile = [path stringByAppendingPathComponent:#"timetableXML.zip"];
if ([fileManager fileExistsAtPath:pathToMyFile]) {
// file exists
NSLog(#"YES a file exist with ZIP extension");
NSLog(#"Unziped successfully!");
path1 = pathToMyFile;
[self unzipFile:path1];
}
else {
NSLog(#"NO such a file exist");
}
});
}
When writing the file the path is created with this code:
dataPath = [path stringByAppendingPathComponent:#"timetableXML.zip"];
dataPath = [dataPath stringByStandardizingPath];
but when testing the path is created with this code which is not the same:
NSString *pathToMyFile = [path stringByAppendingPathComponent:#"timetableXML.zip"];
NSLog() both paths and try to find the problem.
Look and see if the file was written.
Note, there there was no check of the status of the writeToFile: method, add that error check.

When we open pdf in iPhone then how to save this pdf in iphone

I am very new to iOS. I create PDF and load this PDF on UIWebView
now this time I want to save or download this PDF in iPhone when we tapped download button then all exits PDF supporter show like as open ibook ,open in chrome. This type of option show but when we tap any one then my application closed.
-(void)show_Button
{
NSArray *docDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDirectory = [docDirectories objectAtIndex:0];
NSString *filePAth = [docDirectory stringByAppendingPathComponent:#"myPDF.pdf"];
NSLog(#"filePath = %#", filePAth);
NSURL *url2 = [NSURL fileURLWithPath:filePAth];
NSLog(#"url2 = %#", url2);
UIDocumentInteractionController *docContr = [UIDocumentInteractionController
interactionControllerWithURL:url2];
docContr.delegate=self;
[docContr presentOpenInMenuFromRect:CGRectZero inView:self.view animated:YES];
}
so how to save or download this pdf in Iphone please solve this problem....
I believe you can simple use the belo two line:
NSData *myFile = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"your_url"]];
[myFile writeToFile:[NSString stringWithFormat:#"%#/%#", [[NSBundle mainBundle] resourcePath], #"yourfilename.pdf"] atomically:YES];
I hope this it will help you,
Saving the pdf into app
NSData * imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: path]];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"pdfname.pdf"];
NSError *writeError = nil;
[imageData writeToFile:filePath options:NSDataWritingAtomic error:&writeError];
if (writeError) {
NSLog(#"Error writing file: %#", writeError); }
Getting the pdf from the NSDocument Directory
NSString *stringPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSArray *filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory error:&error];
for(int i=0;i<[filePathsArray count];i++)
{
NSString *strFilePath = [filePathsArray objectAtIndex:i];
if ([[strFilePath pathExtension] isEqualToString:#"pdf"])
{
NSString *pdfPath = [[stringPath stringByAppendingFormat:#"/"] stringByAppendingFormat:strFilePath];
NSData *data = [NSData dataWithContentsOfFile:pdfPath];
if(data)
{
UIImage *image = [UIImage imageWithData:data];
[arrayOfImages addObject:image];
}
}
}

How to use ogg.framwork in xcode to play audio from url or data

From couple of days I was searching of how to play ogg on iPhone. But not successful. I found this post which points towards precompiled-ogg-vorbis-libraries-for-ios, but I don't know how to use this framework or libraries. I am new in coding. I also found this post
but it plays ogg audio from bundle. I want to play from a given url, like wikipedia audios. any help will be great. Thanks
UPDATE:
I found another library or file which can be use in iOS but, still I don't know how to use in Xcode. Ogg Vorbis I audio decoder by Sean Barrett. Any idea how to use this.
UPDATE 2:
Just tried to use it something like this, but output file have no sound. Any idea where I am going wrong.
NSString *file = #"http://upload.wikimedia.org/wikipedia/commons/b/b2/En-us-Pakistan.ogg";
NSURL *fileURL = [NSURL URLWithString:file];
NSData * data = [NSData dataWithContentsOfURL:fileURL];
unsigned char* array = (unsigned char*) [data bytes];
int len = [data length];
if (data != nil) {
NSLog(#"\nis not nil");
//NSString *readdata = [[NSString alloc] initWithContentsOfURL:(NSData *)data ];
stb_vorbis* Stream = stb_vorbis_open_memory(array, len, NULL, NULL);
if (Stream)
{
stb_vorbis_close(Stream);
//return true;
}
else
{
//return false;
}
}
Byte *byteData = (Byte*)malloc(len);
memcpy(byteData, [data bytes], len);
NSData *ddata = [NSData dataWithBytes:byteData length:len];
if (ddata == nil) {
NSLog(#"data nil");
}
else{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"wikiaudio"];
NSError *error;
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder if it doesn't already exist
NSString * filename = [#"hello" stringByAppendingString:#".mp3"];
NSString *filePath = [NSString stringWithFormat:#"%#/%#", dataPath,filename];
[ddata writeToFile:filePath atomically:YES];
NSLog(#"filepath %#", filePath);
}

iOS encode/decode views and images to file in Documents directory

I have an object that has an NSMutableArray of custom UIViews, a UIImage, and a couple of strings.
I take that object and shove it into a dictionary. The dictionary gets shoved into an NSData then I do this:
NSString *path;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
path = [paths objectAtIndex:0];
NSString *fileName = DATA;
path = [path stringByAppendingPathComponent:fileName];
NSMutableData *data = [[NSMutableData alloc]init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data];
[archiver encodeObject:dict forKey: DATA];
[archiver finishEncoding];
[[NSFileManager defaultManager] createFileAtPath:path
contents:data
attributes:nil];
It saves successfully. When I try and load the data, the file system shows that my object was saved, but when I try and decode, it says my data is NULL.
Here is my decode code:
-(NSDictionary*)loadData
{
NSString *path;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
path = [paths objectAtIndex:0];
NSArray *directoryContent = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:NULL];
if (directoryContent != nil && [directoryContent count] > 0)
{
NSLog(#"CONTENT COUNT: %d",[directoryContent count]);
NSString *fileName = DATA;
path = [path stringByAppendingPathComponent:fileName];
NSData *data = [[NSMutableData alloc]initWithContentsOfFile:[directoryContent objectAtIndex:0]];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
NSDictionary *dict = [unarchiver decodeObjectForKey: DATA];
[unarchiver finishDecoding];
return dict;
}
else
return nil;
}
My app allows the user to move a bunch of views around and I am just trying to find a simple way to store the Views frames and transforms without having to extract every int/string value. I also was hoping to not have to break down my UIImage into a byte array and then reload it back into an UIImage.
Am I doing crazy stuff here, hoping for functionality that isn't possible?
Is my only option to break down each UIView in the array into separate values for transforms, frames, etc?
Thoughts?
Does the document directory contain anything besides your data file? (I believe that it always contains at least a subdirectory named "Inbox".) I noticed these lines in your loadData method:
path = [path stringByAppendingPathComponent:fileName];
NSData *data = [[NSMutableData alloc]initWithContentsOfFile:[directoryContent objectAtIndex:0]];
You append fileName to path, but then you don't use it. You just read from the first file mentioned in directoryContent.

downloading files using UI web view

Is it possible to download files implementing UI web iphone in my app? If so where would the files be stored and how can I access it?
You can't really download files simply by browsing to them but what you could do is use
(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
to analyze the link for a file (say by looking at the extension of last path component) and if you want this kind of file to be downloaded than you could use [NSURLConnection connectionWithRequest:myURLRequest delegate:self]; and all its associated delegate methods to download and store the file in the documents folder.
if you want to visualize some known for webview file, it will show you automatically...but if page give back an unknown for webview file (This happened to me with Citrix ica file) webview will give you an error....to solve this problem i used this code (note that here i will allow to download only ica file, but you can change this condition):
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
if([error code]!=102)
{ [self.lblError setText:[NSString stringWithFormat:#"%#",error]];
return;
}
NSDictionary *userInfo = [error userInfo];
NSString * url = [[NSString alloc] initWithFormat:#"%#",[userInfo objectForKey:#"NSErrorFailingURLKey"] ];
NSString *search = #"?";
NSRange result = [url rangeOfString:search];
NSInteger startingPosition;
NSString *fileName,*fileExtention,*fileLocation;
if (result.location != NSNotFound) {
startingPosition = result.location + result.length;
fileLocation = [url substringToIndex:result.location];
fileExtention=[fileLocation pathExtension];
}
else
{
fileLocation=url;
}
fileName = [fileLocation lastPathComponent];
fileExtention=[fileLocation pathExtension];
//check if file to download if ica file
if(![fileExtention isEqualToString:#"ica"])
return;
self.lblError.textColor=[UIColor blackColor];
self.lblError.text=[NSString stringWithFormat:#"downloading %#...",fileName];
NSURL * _url = [[NSURL alloc] initWithString:url];
// Get file online
NSData *fileOnline = [[NSData alloc] initWithContentsOfURL:_url];
// Write file to the Documents directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
if (!documentsDirectory) {
// NSLog(#"Documents directory not found!");
return;
}
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:fileName];
//NSLog(#"appFile path: %#",appFile);
[fileOnline writeToFile:appFile atomically:YES];
NSURL* aUrl = [NSURL fileURLWithPath:appFile];
self.interactionController = [UIDocumentInteractionController interactionControllerWithURL: aUrl];
self.interactionController.delegate = self;
self.lblError.text=[NSString stringWithFormat:#"%# downloaded",fileName];
[self.interactionController presentOpenInMenuFromRect:self.lblError.frame inView:self.view animated:YES];
}