How save images in home directory? - iphone

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;
}

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];
}

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 generate pdf using NSData or using data bytes objective c?

Hi I want to write pdf using NSData or using data bytes given by webservice ?
-(NSData *)saveData:(NSData*)fileData fileName:(NSString *)fileName fileType:(NSString *)fileType
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#.%#",documentsDir,fileName,fileType];
NSData* downloadData = [NSData dataWithData:fileData];
[fileManager createFileAtPath:filePath contents:downloadData attributes:nil];
}
I am using this but it's not working it's give me error "It may be damaged or use a file format that Preview doesn’t recognize." on opening that pdf created by above code.
you can convert NSData to PDF with bellow code... I get the bellow Code From This link
NSString *string=[NSString stringWithFormat:#"%#.pdf",[yourArray objectAtIndex:pageIndex]];
[controller1 addAttachmentData:pdfData mimeType:#"application/pdf" fileName:string];
[self presentModalViewController:controller1 animated:YES];
[controller1 release];
//to convert pdf to NSData
NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:#"test.pdf"];
NSData *myData = [NSData dataWithContentsOfFile:pdfPath];
//to convert NSData to pdf
NSData *data = //some nsdata
CFDataRef myPDFData = (CFDataRef)data;
CGDataProviderRef provider = CGDataProviderCreateWithCFData(myPDFData);
CGPDFDocumentRef pdf = CGPDFDocumentCreateWithProvider(provider);
-(IBAction)saveasPDF:(id)sender{
NSString *string=[NSString stringWithFormat:#"%#.pdf",[yourArray objectAtIndex:pageIndex]];
[controller1 addAttachmentData:pdfData mimeType:#"application/pdf" fileName:string];
[self presentModalViewController:controller1 animated:YES];
[pdfData writeToFile:[self getDBPathPDf:string] atomically:YES];
}
-(NSString *) getDBPathPDf:(NSString *)PdfName {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:PdfName];
}
Summary:
get NSData from pdf file path
NSData *pdfData = [NSData dataWithContentsOfFile:pathToFile1];
NSLog(#"pdfData= %d", pdfData != nil);
write NSData to pdf file
[pdfData writeToFile:pathToFile2 atomically:YES];
#ChallengerGuy (If you are still looking for the Swift 2 approach for the CGPDFDocument)
//to convert data of type NSData
guard let cfData = CFDataCreate(kCFAllocatorDefault, UnsafePointer<UInt8>(data.bytes), data.length) else { return nil}
let cgDataProvider = CGDataProviderCreateWithCFData(cfData)
guard let cgPDFDocument = CGPDFDocumentCreateWithProvider(cgDataProvider) else { return nil }
Hope the above helps

How to retrieve UIImage from particular folder in document directory in iPhone

I have used the below function to store images locally in a folder created in document directory
NSError *error;
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
// FOR STORING IMAGE INTO FOLDER CREATED IN DOCUMENT DIRECTORY
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"/ImagesFolder"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error];
NSData* imageData = UIImagePNGRepresentation(imageView.image);
NSString* incrementedImgStr = [NSString stringWithFormat:#"Image%d.png",delegate.dirCountImages];
NSString* fullPathToFile2 = [dataPath stringByAppendingPathComponent:incrementedImgStr];
[imageData writeToFile:fullPathToFile2 atomically:NO];
However how do i retrieve images from that particular folder in document directory
-(NSMutableArray*)getPhotoFileNames:(NSString*)parentFolderName
{
NSString *path = [NSString stringWithFormat:#"%#/%#",[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES)objectAtIndex:0], parentFolderName];
NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:nil];
NSEnumerator *enumerator = [dirContents objectEnumerator];
id fileName;
NSMutableArray *fileArray = [[NSMutableArray alloc] init];
while (fileName = [enumerator nextObject])
{
NSString *fullFilePath = [path stringByAppendingPathComponent:fileName];
NSRange textRangeJpg = [[fileName lowercaseString] rangeOfString:[#".png" lowercaseString]];
if (textRangeJpg.location != NSNotFound)
{
UIImage *originalImage = [UIImage imageWithContentsOfFile:fullFilePath];
[fileArray addObject:originalImage];
}
}
return fileArray;
}
Just need to have the full path and use this method. [[UIImage alloc]initWithContentsOfFile: <#path#>] remember to release the image after if you are not using ARC.
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(100,100,100,100)];
imageView.image = [[UIImage alloc] initWithData:myImage];
[myView addSubview:imageView];
or see that link http://www.iphonedevsdk.com/forum/iphone-sdk-development/23840-placing-image-url-image-view.html
Perhaps this will help you.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
documentsDirectory = [documentsDirectory stringByAppendingPathComponent:#"Images"];
documentsDirectory = [documentsDirectory stringByAppendingPathComponent:#"Image.png"];
[cell.songImageView setImage:[UIImage imageWithContentsOfFile:documentsDirectory]];

check if file exist

i want to check a folder.if i found "test.jpeg" in "path" if it 's true i do nothing but if it false i have to download this picture like that
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[dico objectForKey:#"photo"]]]];
nomPhoto = [[cell.pseudo text]stringByReplacingOccurrencesOfString:#"\n" withString:#""];;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *document = [paths objectAtIndex:0];
filename = [NSString stringWithFormat:#"%#/%#.jpeg",document,nomPhoto];
NSData *data2 = [NSData dataWithData:UIImageJPEGRepresentation(image, 0.1f)];//1.0f = 100% quality
[data2 writeToFile:filename atomically:YES];
EDIT: i try this but don't work. the path is good
NSString* documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* pict = [documentsPath stringByAppendingPathComponent :#"portos"];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:pict];
if (fileExists)
{
NSLog(#"file ok");
}else {
NSLog(#"file ko");
}
thx
Its already answered here.
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:somePath];
If the file specified doesn't exist the CGImage property of UIImage will be nil.
if (image.CGImage) NSLog(#"file ok");
else NSLog(#"file ko");