Image Fetching From The Server and Saving to Documents Folder - ios

I am taking the image as NSData and saving it to Documents Folder.
The problem is, when i try to save it Documents Folder, it saves 2 out of 4, or 3 out of 4. It saves randomly.
I could not figure out where the problem is, since after first failure of saving, the second try may be successful for a particular image.
Could you please help me?
NSData * response = [appDel.serviceHelper serviceCall:#"" withURL:[NSString stringWithFormat:#"%#/Application/GetImage/%#",appDel.appPage.editorServiceURL,ID]];
NSError *error = nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"/Images"];
if(response !=nil)
{
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
{
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error];
}
UIImage *image = [[UIImage alloc] initWithData:response];
NSString *pngFilePath = [NSString stringWithFormat:#"%#/%#",dataPath,[NSString stringWithFormat:#"%#",fileName]];
NSData *data1;
if([pngFilePath rangeOfString:#".png"].location !=NSNotFound)
{
data1 = [NSData dataWithData:UIImagePNGRepresentation(image)];
NSLog(#"png Image");
}
else if([pngFilePath rangeOfString:#".jpg"].location !=NSNotFound)
{
data1 = [NSData dataWithData:UIImageJPEGRepresentation(image,1.0)];
NSLog(#"jpg Image");
}
else
{
NSLog(#"another extension Image");
}
[data1 writeToFile:pngFilePath atomically:YES];
//[appDel.fileHelper writeToFile:response withFileName:fileName];
}

try taking the response as NSMutableDictionary instead of NSData. That might show you what the exception is.

#define DocumentsPath [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]
NSURLSession *defaultNSURLSession ;
CallMethod:
[self downloadImage_WithImageName:#"HERE YOUR FILENAME" FromFileURL:#"HERE IMAGE URL"];
-(void) downloadImage_WithImageName:(NSString *)imageName FromFileURL:(NSString *)fileURL{
NSString *dataPath = [DocumentsPath stringByAppendingPathComponent:#"/Images"];
NSString *filePath=[[NSString alloc] initWithFormat:#"%#/Images/%#",DocumentsPath,imageName];
if (![[NSFileManager defaultManager] fileExistsAtPath:filePath])
{
//NSLog(#"Downloading %# to %#...", fileURL, filePath);
NSURLRequest *request=[[NSURLRequest alloc] initWithURL:[NSURL URLWithString:fileURL]];
NSURLSessionDownloadTask *downTask = [defaultNSURLSession downloadTaskWithRequest:request completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
if (!error) {
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder
NSError *err = nil;
if ([[NSFileManager defaultManager] moveItemAtURL:location toURL:[NSURL fileURLWithPath:filePath] error:&err]) {
//Reload your UITableview or UICollectionView
}else{
NSLog(#"move error %#", error);
}
}else{
NSLog(#"error %#",error);
}
}];
[downTask resume];
} else {
NSLog(#"%# already exists. not downloading.", imageName);
}
}

Related

NSString to PDF file - iOS

I'm receiving a String from a web service and I would like to store it as a pdf file.
I know the have asked before but the answer is always the same. I've tryed it and didn't worked, and it's not explained enough.
So, this is what I'm doing:
NSData *data = [documentString dataUsingEncoding:NSUTF8StringEncoding];
NSString *formattedName = [NSString stringWithFormat:#"%#.pdf", name];
NSString *pdfPath = [#"documents/" stringByAppendingPathComponent:formattedName];
NSError *error = nil;
if([data writeToFile:pdfPath options:NSDataWritingAtomic error:&error]) {
}
It's not entering in the if, and I think the file is not being generated.
I'm working with objective-c, xcode 9.
What should I modify?
Create it
NSError*error=nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"/Application Support"];
NSString*filePathC = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"historyImages"]];
if(![[NSFileManager defaultManager]fileExistsAtPath:filePathC])
{
if(
[[NSFileManager defaultManager] createDirectoryAtPath:filePathC
withIntermediateDirectories:YES
attributes:nil
error:&error])
{
NSLog(#"created");
}
else
{
NSLog(#"not created");
}
}
else
{
NSLog(#"exists");
}
///
NSData *data = [documentString dataUsingEncoding:NSUTF8StringEncoding];
NSString *formattedName = [NSString stringWithFormat:#"%#.pdf", name];
NSString *pdfPath = [filePathC stringByAppendingPathComponent:formattedName];
NSError *error2 = nil;
if([data writeToFile:pdfPath options:NSDataWritingAtomic error:&error2]) {
}

Sometime ERROR copy file from bundle to documents directory in iOS

I am trying to copy a file from my bundle to the documents directory in iOS with the following code.
code:
- (NSString*)getModuleHome{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [[[paths objectAtIndex:0] stringByAppendingPathComponent:#"webapp" ]stringByAppendingPathComponent:#"modules"];
return path;
}
- (void)FirstLoad{
NSError *error;
if (![[NSFileManager defaultManager] fileExistsAtPath:[self getModuleHome]]) {
//建立目录
[[NSFileManager defaultManager] createDirectoryAtPath:[self getModuleHome] withIntermediateDirectories:YES attributes:nil error:nil];
}
NSUserDefaults *userDef = [NSUserDefaults standardUserDefaults];
BLYLogInfo(#"FirstLoad");
NSString *zipPath = [[NSBundle mainBundle] pathForResource:#"" ofType:#"zip"];
NSString *path = NSTemporaryDirectory();
NSString *dataPath = [path stringByAppendingPathComponent:#"modules.zip"];
if ([[NSFileManager defaultManager] fileExistsAtPath:dataPath]) {
BLYLogInfo(#"fileExistsAtPath dataPath");
[[NSFileManager defaultManager] removeItemAtPath:dataPath error:&error];
}
if(![[NSFileManager defaultManager] copyItemAtPath:zipPath toPath:dataPath error:&error])
{
BLYLogError(#"Error copying files: %#", [error localizedDescription]);
[Bugly reportError:error];
}
BLYLogInfo(#"FirstLoad Unzip");
NSString *unZipPath = [path stringByAppendingPathComponent: #"modules"];
if ([[NSFileManager defaultManager] fileExistsAtPath:unZipPath]) {
[[NSFileManager defaultManager] removeItemAtPath:unZipPath error:&error];
}
[SSZipArchive unzipFileAtPath:dataPath toDestination:unZipPath];
BLYLogInfo(#"FirstLoad Copy");
NSString *destinationPath = [self getModuleHome];
BLYLogInfo(#"FirstLoad destinationPath:%#",destinationPath);
if ([[NSFileManager defaultManager] fileExistsAtPath:destinationPath]) {
BLYLogWarn(#"FirstLoad removeItemAtPath");
[[NSFileManager defaultManager] removeItemAtPath:destinationPath error:&error];
}
if (![[NSFileManager defaultManager] copyItemAtPath:unZipPath toPath:destinationPath error:&error]) {
BLYLogError(#"FirstLoad Error copying files: %#", [error localizedDescription]);
[Bugly reportError:error];
NSLog(#"FirstLoad Clean");
[[NSFileManager defaultManager] removeItemAtPath:dataPath error:nil];
[[NSFileManager defaultManager] removeItemAtPath:unZipPath error:nil];
//加载出错
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertView* view = [[UIAlertView alloc] initWithTitle:#"提示"
message:#"抱歉,资源加载失败,请关闭重试"
delegate:self
cancelButtonTitle:nil
otherButtonTitles:nil];
[view show];
});
}
else{
BLYLogInfo(#"FirstLoad Clean");
[[NSFileManager defaultManager] removeItemAtPath:dataPath error:nil];
[[NSFileManager defaultManager] removeItemAtPath:unZipPath error:nil];
[userDef setObject:#"NO" forKey:#"UpdateFlag"];
[userDef synchronize];
[self FirstReload];
}
}
Attach Log:
User Data: NSErrorUserInfo: { NSDestinationFilePath =
"/var/mobile/Containers/Data/Application/3575F3DD-4DC7-4472-A3D0-D4FF86C40BEF/Documents/webapp/modules/ihub/img/cat.png";
NSFilePath =
"/private/var/mobile/Containers/Data/Application/3575F3DD-4DC7-4472-A3D0-D4FF86C40BEF/tmp/modules/ihub/img/cat.png";
NSSourceFilePathErrorKey =
"/private/var/mobile/Containers/Data/Application/3575F3DD-4DC7-4472-A3D0-D4FF86C40BEF/tmp/modules/ihub/img/cat.png";
NSUnderlyingError = "Error Domain=NSPOSIXErrorDomain Code=2 \"No such
file or directory\""; NSUserStringVariant = ( Copy ); }
The app has been released.
Most phones are normal.
Only some phones have this problem.
Each log file reported errors is not the same file not exist.
SAMPLE:
NSError(NSCocoaErrorDomain:4)The
file“contractpayment-detail.html”doesn’t exist。
NSError(NSCocoaErrorDomain:4)The file “vacating.png” doesn’t exist.
NSError(NSCocoaErrorDomain:4)The file “Mode.ts” doesn’t exist.
NSError(NSCocoaErrorDomain:4)The file “SystemCtrl.js” doesn’t exist.
"Why? How to fix it?"
plz try this code
//array of main bundle images
NSMutableArray *array = [[NSMutableArray alloc]initWithObjects:#"admin_1454993109_restaurants_uploaded",
#"admin_1454993149_other_uploaded",
#"admin_1454993170_car_uploaded",
#"admin_1454993206_home_uploaded",
#"admin_1454993235_fashion_uploaded",
#"admin_1454993290_shirt_uploaded",
#"admin_1454993347_electronic_uploaded",
#"admin_1454993380_notes_uploaded", nil];
for (int i = 0; i < array.count; i++) {
// file URL in our bundle
NSURL *fileFromBundle = [[NSBundle mainBundle]URLForResource:[NSString stringWithFormat:#"%#",[array objectAtIndex:i]] withExtension:#"jpg"];
// Destination URL
NSString *path = [self MyImagesDocumentsDirectoryPath];
NSString *filePath = [NSString stringWithFormat:#"%#/%#.jpg",path,[array objectAtIndex:i]];
NSURL *destinationURL = [NSURL fileURLWithPath:filePath];
NSError *error;
if (![[NSFileManager defaultManager] fileExistsAtPath:filePath])
{
// copy it over
[[NSFileManager defaultManager]copyItemAtURL:fileFromBundle toURL:destinationURL error:&error];
NSLog(#"%#",error);
}
}
- (NSString *)MyImagesDocumentsDirectoryPath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"/MyFolder"];
return dataPath;
}
here i am copying the images into MyFolder from Main bundle. you can give your zip files name and use this code.

addSkipBackupAttributeToItemAtURL not working with iOS7

My iOS application just got rejected because the application is storing data on Documents so it is backed up by iCloud, this is not allowed since the data is downloaded from a server.
But even though I'm using addSkipBackupAttributeToItemAtURL it still shows up as a backup to iCloud.Here the code which i have used
NSError *error = nil;
NSData *data = [NSData dataWithContentsOfURL:url options:0 error:&error];
if(!error)
{
[self HidePreLoader];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSLog(#"_paths--->%#",paths);
NSString *path = [paths objectAtIndex:0];
NSLog(#"_path---->%#",path);
NSString *dataPath = [path stringByAppendingPathComponent:#"/MyFolder"];
NSLog(#"_dataPath---->%#",dataPath);
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
{
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error];
}
NSString *zipPath = [dataPath stringByAppendingPathComponent:downfilename];
[data writeToFile:zipPath options:0 error:&error];
if(!error)
{
[self HidePreLoader];
ZipArchive *za = [[ZipArchive alloc] init];
if ([za UnzipOpenFile: zipPath]) {
BOOL ret = [za UnzipFileTo: dataPath overWrite: YES];
if (NO == ret){} [za UnzipCloseFile];
NSLog(#"folderPath--->%#",folderPath);
//Here i have used the use code
NSURL *guidesURL = [NSURL fileURLWithPath:folderPath];
[guidesURL setResourceValue:[NSNumber numberWithBool:YES] forKey:NSURLIsExcludedFromBackupKey error:NULL];
//The following code also doesnt work
//NSURL *guidesURL = [NSURL fileURLWithPath:folderPath];
//[self addSkipBackupAttributeToItemAtURL:guidesURL];
[self HidePreLoader];
NSString *path = nil;
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad)
{
path = [folderPath stringByAppendingPathComponent:#"module-B1-ipadmain-swipe-tablet.html"];
}
else
{
path = [folderPath stringByAppendingPathComponent:#"module-B1-ipadmain-swipe-phone.html"];
}
NSLog(#"path--->%#",path);
dispatch_async(dispatch_get_main_queue(), ^{
appDel.currentReadingPlanWithPath = path;
appDel.moduleDownloaded = YES;
[appDel SetCurrentDownloadPath];
NSLog(#"file download success");
[progview setHidden:YES];
[progval setHidden:YES];
[self HidePreLoader];
downloadView.userInteractionEnabled=YES;
[self SetModuleDownloaded:#"true"];
[self ShowAlert:#"Download" message:#"Success"];
[self HidePreLoader];
});
[self HidePreLoader];
}
}
else
{
NSLog(#"Error saving file %#",error);
}
}
else
{
NSLog(#"Error downloading zip file: %#", error);
}
});
AddSkipBackupAttributeToItemAtURL method
-(BOOL)addSkipBackupAttributeToItemAtURL:(NSURL *)URL
{
assert([[NSFileManager defaultManager] fileExistsAtPath: [URL path]]);
NSError *error = nil;
BOOL success = [URL setResourceValue: [NSNumber numberWithBool: YES]forKey: NSURLIsExcludedFromBackupKey error: &error];
if(!success){
NSLog(#"Error excluding %# from backup %#", [URL lastPathComponent], error);
}
return success;
}
When i try the above code.Still the iCloud shows the application in iOS7.Please help me to solve this issue.
Please check iOS version before using "addSkipBackupAttributeToItemAtURL" function.
Also follow this URL :
https://developer.apple.com/library/ios/qa/qa1719/_index.html
and this URL
https://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/PerformanceTuning/PerformanceTuning.html#//apple_ref/doc/uid/TP40007072-CH8-SW9

Error Domain=NSCocoaErrorDomain Code=512 "The operation couldn’t be completed.The operation couldn’t be completed. Is a directory

I want use writeToFile to store a pic image to the documents, but find the error below, how to solve it ?
Error Domain=NSCocoaErrorDomain Code=512 "The operation couldn’t be completed. (Cocoa error 512.)" {NSFilePath=/Users/alexqdh/Library/Application Support/iPhone Simulator/6.0/Applications/xxx/Documents/girl.png, NSUnderlyingError=0x753e630 "The operation couldn’t be completed. Is a directory"}
-(NSString*)getImagePath:(NSString *)name
{
NSArray *path =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docPath = [path objectAtIndex:0];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *finalPath = [docPath stringByAppendingPathComponent:name];
[fileManager createDirectoryAtPath:finalPath withIntermediateDirectories:YES attributes:nil error:nil];
return finalPath;
}
//below is how to use NSData writeToFile
AFImageRequestOperation *opera = [AFImageRequestOperation imageRequestOperationWithRequest:request imageProcessingBlock:nil
success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
img.image = image;
[self.view addSubview:img];
NSData *imageData = UIImagePNGRepresentation(img.image);
if(imageData == nil)
{
NSLog(#"imageData nil");
}
NSString *picPath = [self getImagePath:#"girl.png"];
NSLog(#"path:%#",picPath);
NSError *error = [[NSError alloc]init];
BOOL a = [imageData writeToFile:picPath options:NSDataWritingAtomic error:&error];
if(a == YES)
{
NSLog(#"YES");
}
else
{
NSLog(#"NO.error:%#", error);
}
/*NSData *imageData = UIImagePNGRepresentation(img.image);
NSString *picPath = [self getImagePath:#"girl.png"];
[imageData writeToFile:picPath atomically:YES];*/
NSLog(#"Got it.code:%d",response.statusCode);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
NSLog(#"Failed pic.error:%#",error);
}];
[opera start];
The problem is caused by creating a directory with the name of the image, then trying to write a file in place of the directory. In other words, you are first creating a directory named:
Documents/girl.png/
then you try to write a file to the path:
Documents/girl.png
Obviously this is not what you meant to do. In your getImagePath: method, get rid of the call to create the directory. The Documents directory will already exist. And of course you don't want a directory corresponding to the filename.
One other option is to change your getImagePath: to:
- (NSString*)getImagePath:(NSString *)name {
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docPath = [path objectAtIndex:0];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *finalPath = [docPath stringByAppendingPathComponent:name];
// Remove the filename and create the remaining path
[fileManager createDirectoryAtPath:[finalPath stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:nil];
return finalPath;
}
This updated code now supports you passing in name values that include subdirectories you might want.

iOS download sqlite database and replace existing one

I have to download the database and replace existing one in the sandbox:
Here's is the presumable way to do that:
DBHelpers *help=[[DBHelpers alloc] init];
NSString *targetPath=[[help DocumentsDirectory] stringByAppendingPathComponent:DATABASE_NAME];
NSLog(#"Target path: %#", targetPath);
NSFileManager *fileManager=[NSFileManager defaultManager];
//if([fileManager fileExistsAtPath:targetPath])
//{
// NSLog(#"Exists");
// return;
}
NSString *sourcePath=[help PathForResource:DATABASE_NAME];
NSLog(#"SourcePath path: %#", sourcePath);
NSError *error;
NSData *data=[NSData dataWithContentsOfURL:[NSURL URLWithString:#"www.hello.com/mydb.sqlite"]];
[data writeToFile:targetPath atomically:NO];
// [fileManager copyItemAtPath:sourcePath toPath:targetPath error:&error];
NSLog(#"Error %#", error);
Consider these steps:
NSData *fetchedData = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://www.myserver.com/files/DBName.sqlite"]]];
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDire ctory, NSUserDomainMask, YES) lastObject];
NSString *filePath = [documentsPath stringByAppendingPathComponent:#"DBName.sqlite"];
[fetchedData writeToFile:filePath atomically:YES];
from iphonedevsdk forum thread.

Resources