File from Documents into NSData - iphone

i want to grab a file from the Documents Directory into a NSData Object, but if i do so my NSData is always NIL:
filepath = [[NSString alloc] init];
filepath = [self.GetDocumentDirectory stringByAppendingPathComponent:fileNameUpload];
NSData *data = [[NSFileManager defaultManager] contentsAtPath:filepath];
-(NSString *)GetDocumentDirectory{
fileMgr = [NSFileManager defaultManager];
homeDir = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
return homeDir;
}
at this point, i always get an exception that my data is NIL:
[request addRequestHeader:#"Md5Hash" value:[data MD5]];
i checked, there´s no File but i dunno why! I created that file before with:
NSMutableString *xml = [[NSMutableString alloc] initWithString:[xmlWriter toString]];
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//make a file name to write the data to using the documents directory:
NSMutableString *fileName = [NSMutableString stringWithFormat:#"%#/7-speed-",
documentsDirectory];
[xml writeToFile:fileName
atomically:NO
encoding:NSStringEncodingConversionAllowLossy
error:nil];
Solved it by:
[xml writeToFile:fileName
atomically:YES
encoding:NSUTF8StringEncoding
error:nil];

check file exists:
if([[NSFileManager defaultManager] fileExistsAtPath:filepath)
{
NSData *data = [[NSFileManager defaultManager] contentsAtPath:filepath];
}
else
{
NSLog(#"File not exits");
}

Swift 3 Version
let filePath = fileURL.path
if FileManager.default.fileExists(atPath: filePath) {
if let fileData = FileManager.default.contents(atPath: filePath) {
// process the file data
} else {
print("Could not parse the file")
}
} else {
print("File not exists")
}

Related

Saving text file to documents directory in iOS 7

I am trying to save a plain text file to the Documents directory in iOS 7. Here is my code:
//Saving file
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSArray *urls = [fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];
NSString *url = [NSString stringWithFormat:#"%#", urls[0]];
NSString *someText = #"Random Text To Be Saved";
NSString *destination = [url stringByAppendingPathComponent:#"File.txt"];
NSError *error = nil;
BOOL succeeded = [someText writeToFile:destination atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (succeeded) {
NSLog(#"Success at: %#",destination);
} else {
NSLog(#"Failed to store. Error: %#",error);
}
Here is the error I am getting:
2013-10-13 16:09:13.848 SavingFileTest[13675:a0b] Failed to store. Error: Error Domain=NSCocoaErrorDomain Code=4 "The operation couldn’t be completed. (Cocoa error 4.)" UserInfo=0x1090895f0 {NSFilePath=file:/Users/Username/Library/Application%20Support/iPhone%20Simulator/7.0-64/Applications/F5DA3E33-80F7-439B-A9AF-E8C7FC4E1630/Documents/File.txt, NSUserStringVariant=Folder, NSUnderlyingError=0x10902aeb0 "The operation couldn’t be completed. No such file or directory"}
I can't figure out why I am getting this error running on the simulator. This works if I use the NSTemporaryDirectory().
From Apple's Xcode Template:
/**
Returns the URL to the application's Documents directory.
*/
- (NSURL *)applicationDocumentsDirectory {
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory
inDomains:NSUserDomainMask] lastObject];
}
You can save like this:
NSString *path = [[self applicationDocumentsDirectory].path
stringByAppendingPathComponent:#"fileName.txt"];
[sampleText writeToFile:path atomically:YES
encoding:NSUTF8StringEncoding error:nil];
Mundi's answer in Swift:
let fileName = "/File Name.txt"
let filePath = self.applicationDocumentsDirectory().path?.stringByAppendingString(fileName)
do {
try strFileContents.writeToFile(filePath!, atomically: true, encoding: NSUTF8StringEncoding)
print(filePath)
}
catch {
// error saving file
}
func applicationDocumentsDirectory() -> NSURL {
return NSFileManager.defaultManager().URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains: NSSearchPathDomainMask.UserDomainMask).last!
}
-(void)writeATEndOfFile:(NSString *)content2
{
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//make a file name to write the data to using the documents directory:
NSString *fileName = [NSString stringWithFormat:#"%#/textfile.txt",
documentsDirectory];
if([[NSFileManager defaultManager] fileExistsAtPath:fileName])
{
NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:fileName];
[fileHandle seekToEndOfFile];
NSString *writedStr = [[NSString alloc]initWithContentsOfFile:fileName encoding:NSUTF8StringEncoding error:nil];
content2 = [content2 stringByAppendingString:#"\n"];
writedStr = [writedStr stringByAppendingString:content2];
[writedStr writeToFile:fileName
atomically:NO
encoding:NSStringEncodingConversionAllowLossy
error:nil];
}
else {
int n = [content2 intValue];
[self writeToTextFile:n];
}
}
-(void) writeToTextFile:(int) value{
//get the documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//make a file name to write the data to using the documents directory:
NSString *fileName = [NSString stringWithFormat:#"%#/textfile.txt",
documentsDirectory];
//create content - four lines of text
// NSString *content = #"One\nTwo\nThree\nFour\nFive";
NSString *content2 = [NSString stringWithFormat:#"%d",value];
content = [content2 stringByAppendingString:#"\n"];
//save content to the documents directory
[content writeToFile:fileName
atomically:NO
encoding:NSStringEncodingConversionAllowLossy
error:nil];
}

Deleting in NSDocumentDirectory

I save in NSDocumentDirectory this way:
NSLog(#"%#", [info objectAtIndex:i]);
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask ,YES );
NSString *documentsDir = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:#"Images%d.png", i]];
ALAssetRepresentation *rep = [[info objectAtIndex: i] defaultRepresentation];
UIImage *image = [UIImage imageWithCGImage:[rep fullResolutionImage]];
//----resize the images
image = [self imageByScalingAndCroppingForSize:image toSize:CGSizeMake(256,256*image.size.height/image.size.width)];
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:savedImagePath atomically:YES];
I know how to delete all the images in NSDocumentDirectory.
But I was wondering on how to delete all of the images with the name of oneSlotImages.
Thanks
Try this ,just copy this code,your images with name oneSlotImages,will be removed from DocumentDirectory ,its just simple :
NSArray *directoryContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject] error:NULL];
if([directoryContents count] > 0)
{
for (NSString *path in directoryContents)
{
NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject] stringByAppendingPathComponent:path];
NSRange r =[fullPath rangeOfString:#"oneSlotImages"];
if (r.location != NSNotFound || r.length == [#"oneSlotImages" length])
{
[[NSFileManager defaultManager] removeItemAtPath:fullPath error:nil];
}
}
}
Have you looked at NSFileManager's methods? Maybe something like this called in a loop for all of your images.
[[NSFileManager defaultManager] removeItemAtPath:imagePath error:NULL];
Use like,
NSArray *dirFiles = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:strDirectoryPath error:nil];
NSArray *zipFiles = [dirFiles filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"self CONTAINS[cd] %#", #"oneSlotImages"]];
The array zipFiles contains the names of all the files we filtered. Thus by appending the filenames with complete path of document directory with in a loop, you can make the full filepath of all the filtered files in the array. Then you can use a loop and call the method of NSFileManager object like below
[fileManager removeItemAtPath: strGeneratedFilePath error: &err];
which removes the itm at path from the directory.
By this way you can filter out the filenames contains oneSlotImages. So you can prefer to delete this ones. Hope this helps you.
As this is an old question now and also above answers shows how to delete by image name.What if I want to delete everything from NSDocumentDirectory at one shot, use the below code.
// Path to the Documents directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
if ([paths count] > 0)
{
NSError *error = nil;
NSFileManager *fileManager = [NSFileManager defaultManager];
// Print out the path to verify we are in the right place
NSString *directory = [paths objectAtIndex:0];
NSLog(#"Directory: %#", directory);
// For each file in the directory, create full path and delete the file
for (NSString *file in [fileManager contentsOfDirectoryAtPath:directory error:&error])
{
NSString *filePath = [directory stringByAppendingPathComponent:file];
NSLog(#"File : %#", filePath);
BOOL fileDeleted = [fileManager removeItemAtPath:filePath error:&error];
if (fileDeleted != YES || error != nil)
{
// Deal with the error...
}
}
}

How save images in home directory?

I am making an application in which i have use Json parsing. With the help of json parsing i get photo url which is saved in string. To show images in my cell i use this code
NSString *strURL=[NSString stringWithFormat:#"%#", [list_photo objectAtIndex:indexPath.row]];
NSData *imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: strURL]];
CGRect myImage =CGRectMake(13,5,50,50);
UIImageView *imageView = [[UIImageView alloc] initWithFrame:myImage];
[imageView setImage:[UIImage imageWithData: imageData]];
[cell addSubview:imageView];
Now prblem is that when i go back or forword then i have wait for few second to come back on same view. Now i want that i when application is used first tme then i wait for that screen otherwise get images from home directory. How i save these image in my home directory? How access from home directory?
You can save an image in the default documents directory as follows using the imageData;
// Accessing the documents directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:#"myImage.png"];
//Writing the image file
[imageData writeToFile:savedImagePath atomically:NO];
You can use this to write a file to your Documents Folder
+(BOOL) downloadFileFromURL:(NSString *) url withLocalName:(NSString*) localName
{
//Get the local file and it's size.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *finalPath = [documentsDirectory stringByAppendingPathComponent:localName];
NSError *error;
NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:finalPath error:&error];
NSAssert (error == nil, ([NSString stringWithFormat:#"Error: %#", error]));
if (error) return NO;
int localFileSize = [[fileAttributes objectForKey:NSFileSize] intValue];
//Prepare a request for the desired resource.
NSMutableURLRequest *request = [NSMutableURLRequest
requestWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"HEAD"];
//Send the request for just the HTTP header.
NSURLResponse *response;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSAssert (error == nil, ([NSString stringWithFormat:#"Error: %#", error]));
if (error) return NO;
//Check the response code
int status = 404;
if ([response respondsToSelector:#selector(statusCode)])
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*) response;
status = [httpResponse statusCode];
}
if (status != 200)
{
//file not found
return NO;
}
else
{
//file found
}
//Get the expected file size of the downloaded file
int remoteFileSize = [response expectedContentLength];
//If the file isn't already downloaded, download it.
if (localFileSize != remoteFileSize || (localFileSize == 0))
{
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
[[NSFileManager defaultManager] createFileAtPath:finalPath contents:data attributes:nil];
return YES;
}
//here we may wish to check the dates or the file contents to ensure they are the same file.
//The file is already downloaded
return YES;
}
and this to read:
+(UIImage*) fileAtLocation:(NSString*) docLocation
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *finalPath = [documentsDirectory stringByAppendingPathComponent:docLocation];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
[[NSFileManager defaultManager] createFileAtPath:finalPath contents:data attributes:nil];
NSData *databuffer = [[NSFileManager defaultManager] contentsAtPath:finalPath];
UIImage *image = [UIImage imageWithData:databuffer];
return image;
}

how to append tags in xml in iphone?

i am new developer in iphone application. i would like write a content in xml file for that, i have created xml file and write tags with element, attribute and value with some data in that xml as follows.
-(void)writexmlfile:(NSString *)data toFile:(NSString *)fileName NodeName:(NSString *)Node{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// the path to write file
NSString *fileExtension = [NSString stringWithFormat:#"%#%#",fileName,#".xml"];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:fileExtension];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:appFile];
if(fileExists) {
NSError *error = nil;
NSString *docStr;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// the path to write file
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:fileName];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:appFile];
if(fileExists)
{
NSLog(#"file exist in document");
NSData *myData1 = [NSData dataWithContentsOfFile:appFile];
if (myData1) {
docStr = [[NSString alloc] initWithData:myData1 encoding:NSASCIIStringEncoding];
XMLString = [[NSMutableString alloc]initWithString:docStr];
[self XMLString];
NSLog(#"data%#",XMLString);
}
}
// [XMLString insertString:data atIndex:index];
[XMLString appendFormat:#"<%#>%#</%#> \n",Node,data,Node];
BOOL success = [XMLString writeToFile:appFile atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (!success) {
NSLog(#"Error: %#", [error userInfo]);
}
else {
NSLog(#"File write is successful");
}
}
}
i want add new tag with new elements,new attributes,etc.,if i enter element at the place of tag it is modifying with previous tag .
here how can i append the new tag to previous appended tags
please any body could help me
Thanks in advance
As a suggestion, you can use APXML to create XML documents it is very simple and easy to use. This post can guide you further.

How to find the contents in documents directory in iPhone

i want to know the contents in a directory either its documents or any other.
if there is a file or more than one i need those file names.
actually i am creating the export directory in documents directory..
and if export is empty then i am copying the zip file from main bundle to export folder
but the following code is not working. though the export is empty its not going in to that if block..r there any hidden files..? and in the last for loop its not doing any thing.
how to do this.
please help me out
self.fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
self.documentsDir = [paths objectAtIndex:0];
//creating folder 'export' to recieve the file from iTunes
NSString *srcFilePath = [NSString stringWithFormat:#"%#/export", self.documentsDir];
[fileManager createDirectoryAtPath:srcFilePath
withIntermediateDirectories:NO
attributes:nil
error:nil];
//copying the zip file into exprort from bundle if export is empty
if(![fileManager fileExistsAtPath:srcFilePath]) {
NSLog(#"File exists at path: %#", srcFilePath);
NSString *resZipfile = [[NSBundle mainBundle] pathForResource:#"sample" ofType:#"zip"
inDirectory:#"pckg"];
NSLog(#"zip file path ...%#", resZipfile);
NSData *mainBundleFile = [NSData dataWithContentsOfFile:resZipfile];
[[NSFileManager defaultManager] createFileAtPath:srcFilePath
contents:mainBundleFile
attributes:nil];
}
NSString *eachPath;
NSDirectoryEnumerator *dirEnum = [fileManager enumeratorAtPath:srcFilePath];
for(eachPath in dirEnum) NSLog(#"FILE: %#", eachPath);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSFileManager *manager = [[NSFileManager alloc] init];
NSDirectoryEnumerator *fileEnumerator = [manager enumeratorAtPath:documentsPath];
for (NSString *filename in fileEnumerator) {
// Do something with file
}
[manager release];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsPath = [paths objectAtIndex:0];
NSString *srcFilePath = [NSString stringWithFormat:#"%#/export", self.documentsDir];
BOOL isDir;
BOOL exists = [[NSFileManager defaultManager] fileExistsAtPath:srcFilePath] isDirectory:&isDir];
if (!exists && !isDir) {
[fileManager createDirectoryAtPath:srcFilePath
withIntermediateDirectories:NO
attributes:nil
error:nil];
NSLog(#"File exists at path: %#", srcFilePath);
NSString *resZipfile = [[NSBundle mainBundle] pathForResource:#"sample" ofType:#"zip"
inDirectory:#"pckg"];
NSLog(#"zip file path ...%#", resZipfile);
NSData *mainBundleFile = [NSData dataWithContentsOfFile:resZipfile];
[[NSFileManager defaultManager] createFileAtPath:srcFilePath
contents:mainBundleFile
attributes:nil];
Swift 4 version:
guard let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first,
let fileEnumerator = fileManager.enumerator(atPath: path) else {
return
}
let fileNames = fileEnumerator.flatMap { $0 as? String } //Here You will have Array<String> with files in current folder and subfolders of your application's Document directory