iPhone - properties of a file [duplicate] - iphone

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
iPhone - file properties
Hi all. i m creating an application which makes the iphone work as a pendrive for easy file sharing purpose.
In the first stage, i have some files(png, pdf, jpg, zip) in a directory and i made them display in the tableview in the form of mutable array without the extensions of each file.
In the second stage i have a detailedViewController which then displays the detailed view of the files like
file size
file type
if it is a image, it should open in imageView
if it is a song, it should play it
So i need to retrieve the properties like filePath, fileType, fileSize.. of each files. Now i got stuck in getting those properties like fileSize and fileType... Please help me proceed with a sample source code.
Here is my code.
- (void)listFiles {
NSFileManager *fm =[NSFileManager defaultManager];
NSError *error = nil;
NSString *parentDirectory = #"/Users/akilan/Documents";
NSArray *paths = [fm contentsOfDirectoryAtPath:parentDirectory error:&error];
if (error) {
NSLog(#"%#", [error localizedDescription]);
error = nil;
}
directoryContent = [[NSMutableArray alloc] init];
for (NSString *path in paths){
documentsDirectory = [[path lastPathComponent] stringByDeletingPathExtension];
NSLog(#"%#", documentsDirectory);
[directoryContent addObject:documentsDirectory];
}
Thanks in advance..

you should use the method attributesOfItemAtPath:error: of your filemanager instance.
Have a look at the documentation.

Related

Data persistance tableView issue iPhone(reading and writing to plist)

In my application I want to implement a simple Alarm function. I know how to use UILocalNotifications, but I came across this source code with a like UI of the iPhone's native Clock app alarm area as well as it having a believe a type of data persistence. Two things I am not good at interface design and data persistence this source code has. But I downloaded it and started playing around with it to find the alarms are not persistent.
Download
Does anyone know how the source code can be adjusted so that it is persistent and the plist can be saved and read to and from? I am open to learning too, this area is somewhat unknown to me too. Thanks
I review your code and find issue that you not moved your "Alarms.plist" file form resource to document directory. we are not able to edit file which is in resource folder. so write following code in app delegate file.
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *theFileName = #"Alarms.plist"; //Change this appropriately
NSString *oldPath = [[NSBundle mainBundle] pathForResource:#"Alarms" ofType:#"plist"];//[NSString stringWithFormat:#"%#/Inbox/%#", documentsDirectory, theFileName];
NSString *newPath = [NSString stringWithFormat:#"%#/%#", documentsDirectory, theFileName];
if (![[NSFileManager defaultManager] fileExistsAtPath:newPath])
[[NSFileManager defaultManager] moveItemAtPath:oldPath toPath:newPath error:nil];
Perform save operation on file which is in Document directory folder.
try this code... to save plist from bundle to Document Directory
Notice that you will have "Unable to read... " just at the first app launch
- (NSMutableArray *)displayedObjects
{
if (_displayedObjects == nil)
{
NSString *path = [[self class] pathForDocumentWithName:#"Alarms.plist"];
NSArray *alarmDicts = [NSMutableArray arrayWithContentsOfFile:path];
if (alarmDicts == nil)
{
NSLog(#"Unable to read plist file: %#", path);
NSLog(#"copy Alarms.plist to: %#", path);
NSString *pathToSetingbundle = [[NSBundle mainBundle] pathForResource:#"Alarms" ofType:#"plist"];
[[NSFileManager defaultManager]copyItemAtPath:pathToSetingbundle toPath:path error:nil];
}
_displayedObjects = [[NSMutableArray alloc]
initWithCapacity:[alarmDicts count]];
for (NSDictionary *currDict in alarmDicts)
{
Alarm *alarm = [[Alarm alloc] initWithDictionary:currDict];
[_displayedObjects addObject:alarm];
NSLog(#"#disply obj %#", alarm);
}
}
return _displayedObjects;
}

Why might this code be giving me null?

Scroll down to EDIT 1. This top bit is irrelevant now.
This is my code:
NSMutableDictionary *dictionary = [self.media objectAtIndex:index];
NSLog(#"dictionary: %#", dictionary);
NSString *originalImagePath = [dictionary objectForKey:#"OriginalImage"];
NSLog(#"path: %#", originalImagePath);
UIImage *originalImage = [UIImage imageWithContentsOfFile:originalImagePath];
NSLog(#"original image: %#", originalImage);
return originalImage;
And my NSLog:
dictionary: {
IsInPhotoLibrary = 1;
MediaType = 0;
OriginalImage = "/var/mobile/Applications/5E25F369-9E05-4345-A0A2-381EDB3321B8/Documents/Images/E9904811-B463-4374-BD95-4AD472DC71A6.jpg";
}
path: /var/mobile/Applications/5E25F369-9E05-4345-A0A2-381EDB3321B8/Documents/Images/E9904811-B463-4374-BD95-4AD472DC71A6.jpg
original image: (null)
Any ideas why this might be coming out as null, despite everything appearing to be in place?
EDIT:
This is the code to write the image to file:
+(NSString *)writeImageToFile:(UIImage *)image {
NSData *fullImageData = UIImageJPEGRepresentation(image, 1.0f);
NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents/Images/"];
NSString *name = [NSString stringWithFormat:#"%#.jpg", [JEntry generateUuidString]];
NSString *filePath = [path stringByAppendingPathComponent:name];
[fullImageData writeToFile:filePath atomically:YES];
NSLog(#"original image 2: %#", [UIImage imageWithContentsOfFile:filePath]);
}
This NSLog also comes out as null. So the problem lies here, most likely. Any ideas?
EDIT 2:
So, back-tracing even more now, and I've realised that it's because this fails:
[fullImageData writeToFile:filePath atomically:YES];
You can return a bool on that line, telling if it was successful or not, and it's returning NO for me. Any ideas why this might be?
EDIT 3:
The image that gets passed in is NULL. Trying to figure out where that's gone wrong now.
Almost certainly your file does not exist. Modify your code as follows to log if a file exists or not:
NSString *originalImagePath = [dictionary objectForKey:#"OriginalImage"];
NSLog(#"path: %#", originalImagePath);
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:originalImagePath];
NSLog(#"file exists: %d", fileExists);
Possible Reasons:
The file at originalImagePath does not exist.
UIImage can not initialize an image from the specified file, because the data is corrupted (maybe the data is empty or incomplete)
the file can not be accessed because of iOS file permissions (i.e. when accessing files beyond the app sandbox)
Have you checked that the image file is really placed on path in dictionary? You may use the iExplorer utility for that.
Also pay attention to the file name case, so it's extension is 'jpg' not 'JPG'.
Finally you should check, whether it's a valid image file, by opening it with some image viewer.
are you sure that the jpg file "E9904811-B463-4374-BD95-4AD472DC71A6.jpg" is there in that folder?
try to open the app file installed in the iPhone/ipad simulator clicking on yourFile.app
with ctrl key and choose to open package contents the open your folder images...
to get a fast link to your documents folder:
NSArray *dirPaths;
NSString *docsDir;
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
NSLog(#"doc:%#",docsDir);
your app should be in its parent folder

iPhone - file properties

i m creating an application which makes the iphone work as a pendrive for easy file sharing purpose.
In the first stage, i have some files(png, pdf, jpg, zip) in a directory and i made them display in the tableview in the form of mutable array. It displays in the tableView as shown below,
.DS_Store
.localized
gazelle.pdf
Hamburger_sandwich.jpg
IITD TAJ Picture 028_jpg.jpg
iya_logo_final_b&w.jpg
manifesto09-eng.pdf
RSSReader.sql
SimpleURLConnections.zip
SQLTutorial
I just want to display the name of the files and i do not want to display the extensions. I know that it is possible to extract the extensions of a file in NSFileManager. But i do not know how. Please help me to make my table view look like this
.DS_Store
.localized
gazelle
Hamburger_sandwich
IITD TAJ Picture 028_jpg
iya_logo_final_b&w
manifesto09-eng
RSSReader
SimpleURLConnections
SQLTutorial
In the second stage i have a detailedViewController which takes displays the detailed view of the file like
file size
file type
if it is a image, it should open in imageView
if it is a song, it should play it
So i need to retrive the properties like filePath, fileType, fileSize.. of each files. Please guide me with a tutorial if possible. I too do not have any idea how to convert a mutableArray to a NSString and call the methods like stringByDeletingPathExtension. Please help me. I can even send my source code if needed. If possible, guide me with some example codes and tutorial.
This should work:)
This will get all files in a directory in a NSString *parentDirectory, get its size, if image do something otherwise it assumes is a sound file
NSFileManager *fm = [NSFileManager defaultManager];
NSError *error = nil;
NSArray *filePaths = [fm contentsOfDirectoryAtPath:parentDirectory error:&error];
if (error) {
NSLog(#"%#", [error localizedDescription]);
error = nil;
}
for (NSString *filePath in filePaths) {
//filename without extension
NSString *fileWithoutExtension = [[filePath lastPathComponent] stringByDeletingPathExtension];
//file size
unsigned long long s = [[fm attributesOfItemAtPath:[parentDirectory stringByAppendingPathComponent:filePath]
error:NULL] fileSize];
UIImage *image = [UIImage imageNamed:[parentDirectory stringByAppendingPathComponent:filePath];];
//if image...
if(image){
//show it here
}
else{
//otherwise it should be music then, play it using AVFoundation or AudioToolBox
}
}
I hope you will have the file name in NSURL object, if so then you can use the following code to get just the file name and can remove the file extension from the string.
NSArray *fileName = [[fileURL lastPathComponent] componentsSeparatedByString:#"."];
NSLog(#"%#",[fileName objectAtIndex:0]);

Loading a web page in iphone and check history

Pseudo code
pageUrl = "http://www.google.com"
if(pageUrl == never Downloaded)
Download pageUrl
else
{
Display Saved Version
Mean while download pageUrl
When done display new version
}
How can I do something like this in objective C for a UIWebview?
Also what's the best way to save web pages for this scenario? PList, SQLite?
Plist is the best way to solve your problem.
iPhone/Objective-c can access very quickly to plist file as compare to SQLite Database.
Let me give you some sample code.
See - edit After some time.
Edit :
Steps for Creating project & connecting web-view
Create New Project -> View Based Application.
Give name "yourProjName" ( up to you what you give )
Open "yourProjNameViewController.xib"
Drag & drop UIWebView
Open "yourProjNameViewController.h" File
Place a variable IBOutlet UIWebView *wView;
Connect in interface builder
Steps for adding Property list file to your project
Expand Resources Group under your project tree
Right click on "Resources" -> Add -> New File
Select Template Category - osx -> Resource
Select Property List file
Give file name "LoadedURL.plist"
Change Root type to Array
Save "LoadedURL.plist" file
Now place following code to "yourProjNameViewController.m" file.
#import "yourProjNameViewController.h"
#define documentsDirectory_Statement NSString *documentsDirectory; \
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); \
documentsDirectory = [paths objectAtIndex:0];
#implementation WebViewLoadViewController
- (void)viewDidLoad {
[super viewDidLoad];
// your url to load
NSString *strToLoad=#"http://www.mail.yahoo.com";
// file management code
// copy file to documents directory
documentsDirectory_Statement;
NSFileManager *fm=[NSFileManager defaultManager];
if(![fm fileExistsAtPath:[documentsDirectory stringByAppendingPathComponent:#"LoadedURL.plist"]]){
[fm copyItemAtPath:[[NSBundle mainBundle] pathForResource:#"LoadedURL" ofType:#"plist"]
toPath:[documentsDirectory stringByAppendingPathComponent:#"LoadedURL.plist"]
error:nil];
}
// array from doc-dir file
NSMutableArray *ar=[NSMutableArray arrayWithContentsOfFile:[documentsDirectory stringByAppendingPathComponent:#"LoadedURL.plist"]];
// check weather file has url data or not.
BOOL fileLocallyAvailable=NO;
NSString *strLocalFileName=nil;
NSUInteger indexOfObject=0;
if([ar count]>0){
for (NSDictionary *d in ar) {
if([[d valueForKey:#"URL"] isEqualToString:strToLoad]){
fileLocallyAvailable=YES;
strLocalFileName=[d valueForKey:#"FileName"];
break;
}
indexOfObject++;
}
}
if(fileLocallyAvailable){
NSDictionary *d=[ar objectAtIndex:indexOfObject];
strLocalFileName=[d valueForKey:#"FileName"];
} else {
NSMutableDictionary *d=[NSMutableDictionary dictionary];
[d setValue:strToLoad forKey:#"URL"];
NSString *str=[[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:strToLoad]];
[str writeToFile:[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%02i.htm",[ar count]]]
atomically:YES
encoding:NSUTF8StringEncoding error:nil];
strLocalFileName=[NSString stringWithFormat:#"%02i.htm",[ar count]];
[d setValue:[NSString stringWithFormat:#"%02i.htm",[ar count]] forKey:#"FileName"];
[ar addObject:d];
[ar writeToFile:[documentsDirectory stringByAppendingPathComponent:#"LoadedURL.plist"]
atomically:YES];
}
NSURL *u=[[NSURL alloc] initFileURLWithPath:[documentsDirectory stringByAppendingPathComponent:strLocalFileName]];
NSURLRequest *re=[NSURLRequest requestWithURL:u];
[wView loadRequest:re];
[u release];
}
`

How can we clear the cached images when we clos the app?

I cache the images to the document directory of my app using the following code.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *saveDirectory = [paths objectAtIndex:0];
But even after I close the application, its still there. How can I clear it when I lose my app. I am doing all this in my simulator.
I would implement applicationWillTerminate: in my application delegate and remove the cache files there. Or better yet, as suggested by Vladimir, save them in a temporary directory and let the OS clean them up when needed.
- (void)applicationWillTerminate:(UIApplication *)app
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *cacheFiles = [fileManager contentsOfDirectoryAtPath:saveDirectory error:error];
for (NSString *file in cacheFiles) {
error = nil;
[fileManager removeItemAtPath:[saveDirectory stringByAppendingPathComponent:file] error:error];
/* handle error */
}
}
If you do not want your cached images to be preserved after application is closed better save them to temporary directory - they will be removed automatically.
If you want to manually remove the files you must store the paths for them and use the following NSFileManager function:
- (BOOL)removeItemAtPath:(NSString *)path error:(NSError **)error
Edit: sorry, I appeared to be wrong here about automatic deleting. Here's a quote from Developing Guide:
Use this directory to write temporary files that you do not need to persist between launches of your application. Your application should remove files from this directory when it determines they are no longer needed. (The system may also purge lingering files from this directory when your application is not running.)
NSString *file;
NSDirectoryEnumerator *dirEnum = [[NSFileManager defaultManager] enumeratorAtPath:saveDirectory];
NSError* err;
while (file = [dirEnum nextObject]) {
err = nil;
[[NSFileManager defaultManager] removeItemAtPath:[saveDirectory stringByAppendingPathComponent:file] error:&err]];
if(err){
//print some errror message
}
}
Use the temporary directory path as specified in this question:
How can I get a writable path on the iPhone?