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]);
Related
I want to load a webpage when user connected to network and store it offline(including with images/resources). If the user not connected to any network then i should load the previously stored webpage. I have tried NSData dataWithContentsOfURL:(NSURL *)url and NSString stringWithContentsOfURL but these stores only html content not the resources.
Thanks in advance.
You can do that with ASIHttpRequest. If you do not want to to use that project (it is no longer active) you can look into the code and what it does. Look at "how to cache a whole web page with images in iOS" for more info as well.
I think the simple solution is this - "Safari Client-Side Storage and Offline Applications Programming Guide", https://developer.apple.com/library/archive/documentation/iPhone/Conceptual/SafariJSDatabaseGuide/Introduction/Introduction.html
Only if you are making an app with HTML5 and webview, didn't test this method yet so far, so it might work.
Write this data into file using:
-(void)writeDataToFile:(NSString*)filename
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
if(filename==nil)
{
DLog(#"FILE NAME IS NIL");
return;
}
// the path to write file
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat: #"%#",filename]];
/*NSData *writeData;
writeData=[NSKeyedArchiver archivedDataWithRootObject:pArray]; */
NSFileManager *fm=[NSFileManager defaultManager];
if(!filePath)
{
//DLog(#"File %# doesn't exist, so we create it", filePath);
[fm createFileAtPath:filePath contents:self.mRespData attributes:nil];
}
else
{
//DLog(#"file exists");
[self.mRespData writeToFile:filePath atomically:YES];
}
NSMutableData *resData = [[NSMutableData alloc] init];
self.mRespData=resData;
[resData release];
}
and load it next time.
I don't know if there is one-line-solution like myWebView.cache4Offline = YES; , but I fear as long as you don't have access to the website's code (i.e. if you want to make any website available offline inside your app), you have to program this on your own. Thinking about it, it doesn't seem so difficult:
Scan the html string for image urls (and everything else you need)
Download those resources from the internet using NSData dataWithContentsOfURL (maybe a little annoying, because of relative/absolute URLs)
Save data to file with NSData writeToFile:options:error:
Replace URL in HTML with filePath from 3. (OR, better use a convention for converting their URLs in your file-URLs)
Hope it helps
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
Hi i am trying to save text values as binary file and read from that file. i am using following code, i got the binary file in documents directory but when reading data from file only got some numbers please kindly help its urgent.
For writing
NSString *documentsDirectoryPath = [self performSelector:#selector(tempDirectoryPath:) withObject:fileName_];
NSLog(#"%#",documentsDirectoryPath);
if ([[NSFileManager defaultManager] isWritableFileAtPath:documentsDirectoryPath]) {
NSLog(#"content =%#",data_);
[data_ writeToFile:documentsDirectoryPath atomically:YES];
return YES;
}
For reading i use the following code,
NSString *documentsDirectoryPath = [self performSelector:#selector(tempDirectoryPath:) withObject:fileName_];
if ([[NSFileManager defaultManager] isReadableFileAtPath:documentsDirectoryPath]) {
NSMutableData *data_ = [NSMutableData dataWithContentsOfFile:documentsDirectoryPath];
return data_;
}
I got only numbers from the data_ .
How to read the .bin file correctly.?
I got the .bin file when extract get .bin.cpgz file.I can't open the file what is the reason ?Is anything wrong in code?
I am pass string in this way:
[self writeData:#"test string is here" toFile:#"mf.bin"];
Thanks.
It's a little late, but something like this might help you:
http://snippets.aktagon.com/snippets/475-How-to-use-NSKeyedArchiver-to-store-user-settings-on-the-iPhone
Sounds like you need to convert the data into something readable.
NSString *myFile = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
This assumes originally the data you wrote was a NSString, if it was an object you would have to use the appropriate methods for that object.
I want to write data to a .txt file without replacing its older contents.I have moved the file from the NSMainBundle to the documents directory.I am able to write the the file by using the code
NSData *data=[NSKeyedArchiver archivedDataWithRootObject:recentMainArray];
NSFileHandle *myHandle = [NSFileHandle fileHandleForUpdatingAtPath:filePath];
[myHandle seekToEndOfFile];
[myHandle writeData:data];
[myHandle closeFile];
But when i try to display the contents of the file,i don't have any data in that.File exists in that path also.This is the following code i use to display the contents.
NSFileManager *manager = [NSFileManager defaultManager];
//filePath - > the documents directory file path
if([manager fileExistsAtPath:filePath]) {
NSMutableArray *savedArray = [[NSMutableArray alloc] initWithContentsOfFile:filePath];
NSMutableArray *storedRecentID = [savedArray objectAtIndex:0];
NSMutableArray *storedRecentName = [savedArray objectAtIndex:1];
NSLog(#"ID:%#",[savedArray objectAtIndex:0]);
NSLog(#"Name:%#",[savedArray objectAtIndex:1]);
}
else {
NSLog(#"file not found, save something to create the file");
}
"null" which is printed as result for those two nslogs.
Please anybody let me know a solution for this problem.FYI,i am using a simulator to test,is this creating a problem.Please suggest me a solution.I have searched a lot and i am not able to find a solution.
Thank you all in advance
Read the data into some Mutable structure (dictionary, array, string) and then append your new data into the same satring. Now write the data into the same path. So the new appended data will be written in file.
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.