How come writeToFile does not write over original file? - ios

I am saving a file like this in my iOS App in my UIImagePickerDelegate's method didFinishPIckingMediaWithInfo:
// write
NSString* filePath = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:#"Documents/invoice.jpeg"]];
NSData *imageData = UIImageJPEGRepresentation(info[UIImagePickerControllerOriginalImage], 0.0);
if (imageData != nil) {
[imageData writeToFile:filePath atomically:YES];
}
Then I am retrieving the file like this:
// load
NSString *searchFilename = #"invoice.jpeg";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSDirectoryEnumerator *direnum = [[NSFileManager defaultManager] enumeratorAtPath:documentsDirectory];
NSString *documentsSubpath;
while (documentsSubpath = [direnum nextObject])
{
if (![documentsSubpath.lastPathComponent isEqual:searchFilename]) {
continue;
}
NSURL *fileURL = [[NSURL alloc]initFileURLWithPath:[NSString stringWithFormat:#"%#/%#",documentsDirectory,documentsSubpath]];
[self.imageContentView setupImageViewerWithImageURL:fileURL onOpen:^{
NSLog(#"open %#",fileURL);
} onClose:^{
NSLog(#"close %#",fileURL);
}];
}
The files do get loaded properly. However, when I update the photo (imageData) in my UIImagePickerDelegate and try to reload the image, I still get the original image written into my app documents.

Related

How to check the audio is stored locally and run it without downloading?

In this code, the audio is downloaded every time when I click on a button. I want to do check audio stored locally. If stored as run it without loading. How can I do this?
- (void) song{
NSString *stringURL = #"https://drive.google.com/uc?export=download&id=0B6zMam2kAK39VHZ1cUZsM3BhQXM";
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,#"music.mp3"];
[urlData writeToFile:filePath atomically:YES];
}
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,#"music.mp3"];
self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL URLWithString:filePath] error:nil];
}
NSFileManager has the following methods:
- (BOOL)fileExistsAtPath:(NSString *)path;
- (BOOL)fileExistsAtPath:(NSString *)path isDirectory:(nullable BOOL *)isDirectory;
- (BOOL)isReadableFileAtPath:(NSString *)path;
- (BOOL)isWritableFileAtPath:(NSString *)path;
- (BOOL)isExecutableFileAtPath:(NSString *)path;
- (BOOL)isDeletableFileAtPath:(NSString *)path;
So we check like this:
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"music.mp3"];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:filePath isDirectory:NO];
if (!fileExists) {
// start the download process here then save
[urlData writeToFile:filePath atomically:YES];
}

How to check if a file is download?

How can I check if a file is download and save on device? Help me please.
- (void) song{
if (_index1 == 0) {
NSString *stringURL = #"https://drive.google.com/uc?export=download&id=0B0EJbcHq3ZALWUo0a05LMWNzeDg";
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,#"music.mp3"];
[urlData writeToFile:filePath atomically:YES];
self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL URLWithString:filePath] error:nil];
}
}
}
If you want to see if the file music.mp3 is in your Documents folder:
NSString *filePath = [documentsDirectory stringByAppendingPathComponent#"music.mp3"];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:filePath];
This only makes sense if that file is always the same file. If it can be different files then you need to associate the URL you use to download with the file you stored it in.

Saving many pdf locally on device and retrieving it on click

NSURL *url = [NSURL URLWithString:#"PDFLINK"];
// Get the PDF Data from the url in a NSData Object
NSData *pdfData = [[NSData alloc] initWithContentsOfURL:url];
NSString * name = #"First";
// Store the Data locally as PDF File
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *newFilePath = [documentsDirectory stringByAppendingPathComponent:#"my.pdf"];
NSError *error;
if ([fileManager createFileAtPath:newFilePath contents:pdfData attributes:nil])
{
NSLog(#"Create Sucess");
[self loadPDF];
}
else
{
NSLog(#"Create error: %#", error);
}
}
-(void)loadPDF
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSArray *resultArray = [fileManager subpathsOfDirectoryAtPath:documentsDirectory error:nil];
if (![resultArray containsObject:arrObj])
{
// do something
}
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:[resultArray objectAtIndex:0]];
// Now create Request for the file that was saved in your documents folder
//NSLog(#"The filePath %#",filePath);
NSURL *url = [NSURL fileURLWithPath:filePath];
NSLog(#"The url %#",url);
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[_webView setUserInteractionEnabled:YES];
[_webView setDelegate:self];
[_webView loadRequest:requestObj];
}
Here is my code.I have more 10 pdf and want to store them locally on device and display next time without download.
It saves the pdf again and i cannot check whether it is downloaded or not ?
Please help me
I am not sure what you mean but, to download a file , you need to use NSData:
NSString *stringURL = #"your file URL";
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,#"filename.extension"];
[urlData writeToFile:filePath atomically:YES];
}
Now the downloaded file exists at filePath and you can get it by using:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"filename with extension"];
NSString *content = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];
you can try this to check if file exists at file path:
NSString* documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* file = [documentsPath stringByAppendingPathComponent:#"filename"];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:file];
if(fileExists){
//dont download, just grab it and display it
}
else{
//download and display it
}

ios save audio and video url into document directory

I need to save all of audio and video url's into document directory which comes from the server. i have tried a sample code
NSData *urlData = [NSData dataWithContentsOfURL:[NSURL URLWithString: "http://www.ebookfrenzy.com/ios_book/movie/movie.mp4"]];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dataPath_ = [documentsDirectory stringByAppendingPathComponent:#"/MyFolder"];
NSString *newStr = [#"test" stringByAppendingString:[NSString stringWithFormat:#".mp4"]];
NSString *FilePath = [NSString stringWithFormat:#"%#/%#",dataPath_,newStr];
[urlData writeToFile:FilePath atomically:YES];
The folder is creating in document directory but the video is not saving into the folder.Can anyone help to sort this out.
You should build the path properly and you should do some basic error checking:
NSData *urlData = [NSData dataWithContentsOfURL:[NSURL URLWithString: #"http://www.ebookfrenzy.com/ios_book/movie/movie.mp4"]];
if (urlData) {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"MyFolder"];
// Create folder if needed
[[NSFileManager defaultFileManager] createDirectoryAtPath:dataPath withIntermediateDirectories:YES attributes:nil error:nil];
NSString *filePath = [dataPath stringByAppendingPathComponent:#"test.mp4"];
if ([urlData writeToFile:filePath atomically:YES]) {
// yeah - file written
} else {
// oops - file not written
}
} else {
// oops - couldn't get data
}

How can I make a folder in NSDocument directory where I can save all the photos and delete the data from same folder when I want?

I have a tableView where for each cell I'm getting an image url string and I'm saving all data in the NSDocument directory.
I want to store all the data in folder made in the NSDocument directory and I also want to delete all the contents in that folder later. How to do it?
this is the method I'm using
(void)setThumbnailTo :(UITableViewCell *)cell withRefString:(NSString *)string {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"patientPhotoFolder"];
NSString *imgPath = [string stringByReplacingOccurrencesOfString:#"amp;" withString:#""];
imgPath = [imgPath stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *key = [self sha1:imgPath];
NSString *fileToSave = [documentsPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.jpg",key]];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:fileToSave];
if (!fileExists)
{
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0ul);
dispatch_async(queue, ^{
NSData *imageData=[NSData dataWithContentsOfURL:[NSURL URLWithString:imgPath]];
UIImage *image = [[UIImage alloc] initWithData:imageData];
NSData *jpegData = UIImageJPEGRepresentation(image,4);
[[NSFileManager defaultManager] createFileAtPath:fileToSave contents:jpegData attributes:nil];
dispatch_sync(dispatch_get_main_queue(), ^{
patientPhoto.image = image;
});
});
patientPhoto.image = [UIImage imageNamed:#"patientPhoto.png"];
}else{
UIImage *image = [UIImage imageWithContentsOfFile:fileToSave];
if(!image) image = [UIImage imageNamed:#"patientPhoto.png"];
patientPhoto.image = image;
}
}
How to lazily create a folder named "patientPhotoFolder" in your Documents directory (this could for example be a category on NSFileManager:
- (NSString *)pathToPatientPhotoFolder {
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask,
YES) lastObject];
NSString *patientPhotoFolder = [documentsDirectory stringByAppendingPathComponent:#"patientPhotoFolder"];
// Create the folder if necessary
BOOL isDir = NO;
NSFileManager *fileManager = [[NSFileManager alloc] init];
if (![fileManager fileExistsAtPath:patientPhotoFolder
isDirectory:&isDir] && isDir == NO) {
[fileManager createDirectoryAtPath:patientPhotoFolder
withIntermediateDirectories:NO
attributes:nil
error:nil];
}
return patientPhotoFolder;
}
How to delete the contents of that folder (given you implemented it as a category on NSFileManager):
NSString *patientPhotoFolder = [[NSFileManager defaultManager] pathToPatientPhotoDirectory];
NSArray *contents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:patientPhotoFolder error:nil];
for (NSString *filename in contents) {
[[NSFileManager defaultManager] removeItemAtPath:[patientPhotoFolder stringByAppendingPathComponent:filename] error:NULL];
}

Resources