Corrupt images and pdf with goldraccoon ftp-upload - ios

I use GoldRaccoon for ftp-upload in my iOS-Application. The filetransfer works perfekt with txt-files up to many mb size. But images and pdf-files would be corrupted when they be uploaded.
There is no error and the upload seems to be successfull.
When i look into the iPad in the folder of the application (with iExplorer), there the files are good. Its also equal how big the size of the image is. Also its equal if it is a jpg or a png.
Also the files all existing when I start the upload.
- (void)uploadFilesToFTP:(Objekt *)objekt withCsvFilePath:(NSString *)csvLocalFilePath {
__block typeof(self) bself = self;
[self.library enumerateGroupsWithTypes:ALAssetsGroupAlbum
usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
if ([[group valueForProperty:ALAssetsGroupPropertyName] isEqualToString:self.albumName]) {
InfoLogMy(#"found album %#", self.albumName);
self.groupToAddTo = group;
}
}
failureBlock:^(NSError* error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Fehler" message:[error localizedDescription] delegate:nil cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[alertView show];
return;
}];
// dateien
InfoLogMy("Count of files %d", objekt.dateien.count);
for (Datei *datei in objekt.dateien)
{
InfoLogMy(#"Upload starts");
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dateiPath = [documentsDirectory stringByAppendingPathComponent:datei.dateiname];
NSError *error;
NSData *data = [[NSData alloc] initWithContentsOfFile:dateiPath options:NSDataReadingUncached error:&error];
if( [[NSFileManager defaultManager] fileExistsAtPath:dateiPath] )
{
if (!error) {
if (datei.zimmer != nil) {
// original image
UIImage *originalImage = [UIImage imageWithData:data];
__block typeof(self) bself = self;
//Bild wird in das Photoalbum des iPads als Sicherung abgelegt.
//Dies ist nicht mit PDF-Dokumenten möglich
[self.library writeImageToSavedPhotosAlbum:[originalImage CGImage]
metadata:nil
completionBlock:^(NSURL* assetURL, NSError* error) {
if (error.code == 0) {
// try to get the asset
[self.library assetForURL:assetURL
resultBlock:^(ALAsset *asset) {
// assign the photo to the album
[bself.groupToAddTo addAsset:asset];
}
failureBlock:^(NSError* error) {
InfoLogMy("failed to retrieve image asset:\nError: %# ", [error localizedDescription]);
}];
}
else {
InfoLogMy("saved image failed.\nerror code %i\n%#", error.code, [error localizedDescription]);
}
}];
}
// copy of image
NSString *filenameCopy = [NSString stringWithFormat:#"copy-%#", datei.dateiname];
NSString *localFilePathCopy = [documentsDirectory stringByAppendingPathComponent:filenameCopy];
BOOL copyFileExists = [[NSFileManager defaultManager] fileExistsAtPath:localFilePathCopy];
BOOL hasPaths = ([[datei.zeichnungen allObjects] count] > 0);
BOOL hasSymbols = ([[datei.symbole allObjects] count] > 0);
NSString *fileExtension = [datei.dateiname substringWithRange:NSMakeRange(datei.dateiname.length - 3, 3)];
BOOL isPDF = ([fileExtension isEqualToString:#"pdf"]);
if (copyFileExists == YES && (hasPaths == YES || hasSymbols == YES|| isPDF == YES)) {
NSError *error;
NSData *dataCopy = [[NSData alloc] initWithContentsOfFile:localFilePathCopy options:NSDataReadingUncached error:&error];
if (isPDF == NO) {
UIImage *copyImage = [UIImage imageWithData:dataCopy];
[self.library writeImageToSavedPhotosAlbum:[copyImage CGImage]
metadata:nil
completionBlock:^(NSURL* assetURL, NSError* error) {
if (error.code == 0) {
InfoLogMy(#"saved image completed:\nurl: %#", assetURL);
// try to get the asset
[self.library assetForURL:assetURL
resultBlock:^(ALAsset *asset) {
// assign the photo to the album
[bself.groupToAddTo addAsset:asset];
}
failureBlock:^(NSError* error) {
InfoLogMy(#"failed to retrieve image asset:\nError: %# ", [error localizedDescription]);
}];
}
else {
InfoLogMy(#"saved image failed.\nerror code %i\n%#", error.code, [error localizedDescription]);
}
}];
}
if (!error) {
[self.requestsManager addRequestForUploadFileAtLocalPath:localFilePathCopy toRemotePath:[NSString stringWithFormat:#"%#%#", kFtpPathOutbox, filenameCopy]];
}
}
else
{
//Wenn die Datei keine Zuordnung zu einem Zimmer hat.
if (datei.zimmer != nil)
{
[self.requestsManager addRequestForUploadFileAtLocalPath:dateiPath toRemotePath:[NSString stringWithFormat:#"%#%#", kFtpPathOutbox, datei.dateiname]];
}
}
} else {
// TO DO: Alert mit Fehler
return;
}
}
else
{
InfoLogMy(#"Datei existiert leider nicht");
[Mbs writeLog:[NSString stringWithFormat:#"Datei existiert nicht (%#)", datei.dateiname]];
}
}
NSArray *parts = [csvLocalFilePath componentsSeparatedByString:#"/"];
NSString *remotePath = [NSString stringWithFormat:#"%#%#", kFtpPathOutbox, [parts lastObject]];
[self.requestsManager addRequestForUploadFileAtLocalPath:csvLocalFilePath toRemotePath:remotePath];
self.requestsManagerFailed = NO;
[self.requestsManager startProcessingRequests];
}

Related

ALAssetsLibrary addAssetsGroupAlbumWithName is not working on iOS 9

I need to add group with name "MyGroupName" in ALAssetsLibrary . So I have used below code.
ALAssetsLibrary * library = [[ALAssetsLibrary alloc] init];
__weak ALAssetsLibrary *lib = library;
[library addAssetsGroupAlbumWithName:#"MyGroupName" resultBlock:^(ALAssetsGroup *group) {
[lib enumerateGroupsWithTypes:ALAssetsGroupAlbum
usingBlock:^(ALAssetsGroup *g, BOOL *stop)
{
if ([[g valueForProperty:ALAssetsGroupPropertyName] isEqualToString:#"MyGroupName"]) {
NSLog(#"group created with name 'MyGroupName'");
}
}failureBlock:^(NSError *error){
NSLog(#"failure %#",error);
}
];
} failureBlock:^(NSError *error) {
NSLog(#"failure %#",error);
}];
but inside "enumerateGroupsWithTypes" , group "g" is always nil in iOS 9.3.1 (iphone 6). its working correctly and group created with name "MyGroupName" on iOS 9.3.1 iphone 5. I want to know why above code is not working on iphone 6 and is there any solution to make it work ?
Please help me. Thanks in advance
1) First Import
#import <Photos/Photos.h>
#import <Photos/PHAsset.h>
#import <AssetsLibrary/AssetsLibrary.h>
2) Set property for ALAsset
#property (nonatomic, strong) ALAssetsLibrary* assetsLibrary;
3) Then allocate ALAsset library in your .m file
- (ALAssetsLibrary*)assetsLibrary
{
if (!_assetsLibrary) {
_assetsLibrary = [[ALAssetsLibrary alloc] init];
[ALAssetsLibrary disableSharedPhotoStreamsSupport];
}
return _assetsLibrary;
}
4 ) Now create method for save image to custom album
- (void)saveImageDatas:(UIImage*)imageDatas toAlbum:(NSString*)album withCompletionBlock:(void(^)(NSError *error))block
{
` if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
NSMutableArray* assets = [[NSMutableArray alloc]init];
PHAssetChangeRequest* assetRequest;
#autoreleasepool {
assetRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:imageDatas];
[assets addObject:assetRequest.placeholderForCreatedAsset];
}
__block PHAssetCollectionChangeRequest* assetCollectionRequest = nil;
PHFetchResult* result = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
[result enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
PHAssetCollection* collection = (PHAssetCollection*)obj;
if ([collection isKindOfClass:[PHAssetCollection class]]) {
if ([[collection localizedTitle] isEqualToString:album]) {
assetCollectionRequest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:collection];
[assetCollectionRequest addAssets:assets];
*stop = YES;
}
}
}];
if (assetCollectionRequest == nil) {
assetCollectionRequest = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:album];
[assetCollectionRequest addAssets:assets];
}
}
completionHandler:^(BOOL success, NSError *error) {
if (block) {
block(error);
}
}];
}
else {
__weak ALAssetsLibrary* lib = [self assetsLibrary];
[[self assetsLibrary] writeImageDataToSavedPhotosAlbum:UIImageJPEGRepresentation(imageDatas, 1.0) metadata:nil completionBlock:^(NSURL* assetURL, NSError* error) {
if (error != nil) {
return;
}
__block BOOL albumWasFound = NO;
[lib enumerateGroupsWithTypes:ALAssetsGroupAlbum usingBlock:^(ALAssetsGroup* group, BOOL* stop) {
if ([[group valueForProperty:ALAssetsGroupPropertyName] isEqualToString:album]) {
albumWasFound = YES;
[lib assetForURL:assetURL resultBlock:^(ALAsset* asset){
[group addAsset:asset];
if (block) {
block(nil);
}
}failureBlock:^(NSError* error) {
if (block) {
block(error);
}
}];
return;
}
if (group == nil && albumWasFound == NO) {
[lib addAssetsGroupAlbumWithName:album resultBlock:^(ALAssetsGroup* group) {
} failureBlock:^(NSError* error) {
[lib assetForURL:assetURL resultBlock:^(ALAsset* asset){
[group addAsset:asset];
if (block) {
block(nil);
}
}failureBlock:^(NSError* error) {
if (block) {
block(error);
}
}];
}];
}
} failureBlock:^(NSError* error) {
if (block) {
block(error);
}
}];
}];
}
}
5 ) Now call this method to save the image like
[self saveImageDatas:myimage toAlbum:#"MyGroupName" withCompletionBlock:^(NSError *error) {
if (!error) {
NSLog(#"Sucess");
}
}];
"myimage" is your image that you want to save.
Please try this on:
ALAssetsLibrary* libraryFolder = [[ALAssetsLibrary alloc] init];
[libraryFolder addAssetsGroupAlbumWithName:#"My Album" resultBlock:^(ALAssetsGroup *group)
{
NSLog(#"Adding Folder:'My Album', success: %s", group.editable ? "Success" : "Already created: Not Success");
} failureBlock:^(NSError *error)
{
NSLog(#"Error: Adding on Folder");
}];
Or Please check this link also
http://www.touch-code-magazine.com/ios5-saving-photos-in-custom-photo-album-category-for-download/

Can we upload photos in Adobe Assets using Abode Creative SDK for iOS and Android?

Using this chunk of code only for accessing the Adobe files in my iOS project, but how can I upload my pictures in Adobe Assets cloud and save it.
[[AdobeUXAssetBrowser sharedBrowser]popupFileBrowser:^(AdobeSelectionAssetArray *itemSelections) {
NSLog(#"Selected a file");
for(id item in itemSelections) {
AdobeAsset *it = ((AdobeSelectionAsset *)item).selectedItem;
NSLog(#"File name %#", it.name);
[_statuslabel setText:fileDesc];
//If an image, let's draw it locally
NSString *fileType = ((AdobeAssetFile *)it).type;
if([fileType isEqualToString:#"image/jpeg" ] || [fileType isEqualToString:#"image/png" ]) {
NSLog(#"Going to download the image");
[((AdobeAssetFile *)it) getData:NSOperationQueuePriorityHigh
onProgress:^(double fractionCompleted) {
}
onCompletion:^(NSData *data, BOOL fromcache) {
NSLog(#"Done downloaded");
UIImage *preview = [UIImage imageWithData:data];
}
onCancellation:^(void){
}
onError:^(NSError *error) {
}
];
}
}
} onError:^(NSError *error)
{
//do nothing
NSLog(#"Error");
}];
You can find a tutorial on how to upload and download files from Creative Cloud using the CreativeSDK here:
https://creativesdk.adobe.com/docs/ios/#/articles/files/index.html
The code in particular that deals with file uploads is below:
NSData *imgData = UIImageJPEGRepresentation( yourImage, 0.8f );
NSString *dataPath = [NSTemporaryDirectory() stringByAppendingPathComponent:#"foo.jpg"];
NSURL *dataURL = [NSURL fileURLWithPath:dataPath];
NSError *err;
BOOL success = [imgData writeToFile:dataPath options:NSDataWritingAtomic error:&err];
if (success) {
AdobeAssetFolder *root = [AdobeAssetFolder getRootOrderedByField:AdobeAssetFolderOrderByName orderDirection:AdobeAssetFolderOrderDescending];
[AdobeAssetFile create:#"foo.jpg"
inFolder:root
withDataPath:dataURL
withType:kMimeTypeJPEG
withCollisionPolicy:AdobeAssetFileCollisionPolicyAppendUniqueNumber
onProgress:^(double fractionCompleted) {
NSLog(#"Percent complete %f", fractionCompleted);
}
onCompletion:^(AdobeAssetFile *file) {
NSLog(#"Uploaded");
}
onCancellation:nil
onError:^(NSError *error) {
NSLog(#"error uploading %#", error);
}];
}

Uploading images on Box from iOS Application

I am working with an iOS application in which I have to upload images on Box Service. After authentication process when I uploaded images from the NSBundle, it uploaded successfully.
when I uploaded from a path image get uploaded but only file is created, no data is uploaded.
Below is my uploaded method:
-m(void)uploadimages:(UIImage*)image
{
BoxFileBlock fileBlock = ^(BoxFile *file)
{
[self fetchFolderItemsWithFolderID:self.folderID name:self.navigationController.title];
dispatch_sync(dispatch_get_main_queue(), ^{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"File Upload Successful" message:[NSString stringWithFormat:#"File has id: %#", file.modelID] delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
});
};
BoxAPIJSONFailureBlock failureBlock = ^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSDictionary *JSONDictionary)
{
BOXLog(#"status code: %li", (long)response.statusCode);
BOXLog(#"upload response JSON: %#", JSONDictionary);
};
BoxFilesRequestBuilder *builder = [[BoxFilesRequestBuilder alloc] init];
NSInteger randomNumber = arc4random() % 100;
NSString *filename = [NSString stringWithFormat:#"PicBackMan-%ld.jpg",(long)randomNumber];
builder.name = filename;
builder.parentID = self.folderID;
NSLog(#"builder.parentID : %#",builder.parentID);
NSArray *pathList = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask,
YES);
path = [[pathList objectAtIndex:0] stringByAppendingPathComponent:#"image.jpg"];
NSLog(#"Path o/p is %#",path);
NSInputStream *inputStream = [NSInputStream inputStreamWithFileAtPath: path];
NSLog(#"inputStream DIRECT : %#",inputStream);
NSError *error;
NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:&error];
if (!error) {
if (fileAttributes != nil) {
NSLog(#"File attributes found.");
} else {
NSLog(#"File attributes not found.");
}
} else {
NSLog(#"%#", [error localizedDescription]);
long long contentLength = [[fileAttributes objectForKey:NSFileSize] longLongValue];
NSLog(#"fileAttributes : %#",fileAttributes);
NSLog(#"contentLength : %lld",contentLength);
[[BoxSDK sharedSDK].filesManager uploadFileWithInputStream:inputStream contentLength:contentLength MIMEType:nil requestBuilder:builder success:fileBlock failure:failureBlock progress:nil];
}
I am getting the output, but my file is not uploaded with data, only an image of file with name created.
I am getting following output in log:
builder.parentID : 2323165189
2014-08-19 17:25:58.431 BoxSDKSampleApp[17252:1243051] /Users/bettermac9/Library/Application Support/iPhone Simulator/7.1-64/Applications/30DFB367-599B-4F39-AD62-D27B1081FE99/Documents/image.jpg
2014-08-19 17:25:58.432 BoxSDKSampleApp[17252:1243051] inputStream DIRECT : <__NSCFInputStream: 0x7f8f7ae5db00>
2014-08-19 17:25:58.432 BoxSDKSampleApp[17252:1243051] The operation couldn’t be completed. (Cocoa error 260.)
2014-08-19 17:25:58.432 BoxSDKSampleApp[17252:1243051] fileAttributes : (null)
2014-08-19 17:25:58.432 BoxSDKSampleApp[17252:1243051] contentLength : 0
Please help me out, as per my knowledge I think I am doing any mistake in reading the file from path and sending to NSinputstream. Please help me out.
Thank you

Save recorded video from AVFoundation

I am not able to save the recorder video from AVFoundation... In didfinishcapture I check if file exists in the temporary folder, code always returns NO.
Also, this warning is printed when i stop the recording:
"cannot be saved to the saved photos album: Error Domain=NSOSStatusErrorDomain Code=2 "This movie could not be played." UserInfo=0x1c5696c0 {NSLocalizedDescription=This movie could not be played.}"
#define OP_PATH [NSTemporaryDirectory() stringByAppendingPathComponent:[#"movie" stringByAppendingPathExtension:#"mov"]]
- (IBAction) startSession:(id)sender
{
if(! self.captureSession)
{
//Session
self.captureSession = [[AVCaptureSession alloc] init];
//self.captureSession.sessionPreset = AVCaptureSessionPresetMedium;
//Layer of own view
CALayer *viewLayer = self.captureView.layer;
//AVCaptureVideoPreviewLayer
AVCaptureVideoPreviewLayer *avCaptureLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.captureSession];
avCaptureLayer.frame = self.captureView.bounds;
[self.captureView.layer addSublayer:avCaptureLayer];
//AVCaptureDevice
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
NSError *err = nil;
//Output - Image
self.stillImgOutput = [[AVCaptureStillImageOutput alloc] init];
[self.stillImgOutput setOutputSettings:[NSDictionary dictionaryWithObjectsAndKeys:
AVVideoCodecJPEG, AVVideoCodecKey,
nil]];
[self.captureSession addOutput:self.stillImgOutput];
//Output - Video
self.movieOutput = [[AVCaptureMovieFileOutput alloc] init];
// NSString* key = (NSString*)kCVPixelBufferBytesPerRowAlignmentKey;
//
// NSNumber* value = [NSNumber numberWithUnsignedInt:kCVPixelFormatType_32BGRA];
//
// NSDictionary* videoSettings = [NSDictionary dictionaryWithObject:value forKey:key];
if([self.captureSession canAddOutput:self.movieOutput])
{
NSLog(#"Movie out put added");
[self.captureSession addOutput:self.movieOutput];
}
else
{
NSLog(#"Cannot add movie out put");
}
//Input
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&err];
if(! input)
{
NSLog(#"Error no camera");
return;
}
if([self.captureSession canAddInput:input])
{
[self.captureSession addInput:input];
}
else
{
NSLog(#"Cannot add input. Check Output Settings");
}
}
if(! [self.captureSession isRunning])
{
[self.captureSession startRunning];
}
else
{
NSLog(#"Session already running");
}
}
- (void)captureOutput:(AVCaptureFileOutput *)captureOutput didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL fromConnections:(NSArray *)connections error:(NSError *)error
{
NSLog(#"Did stop recording to - %# \n Any error ? - %#", outputFileURL, [error description]);
if([[NSFileManager defaultManager] fileExistsAtPath:[outputFileURL absoluteString]])
{
NSLog(#"YES file exists");
}
else
{
NSLog(#"NO File does not exist");
}
if(UIVideoAtPathIsCompatibleWithSavedPhotosAlbum([outputFileURL absoluteString]))
{
NSLog(#"YES file is compatible to be saved in Album");
UISaveVideoAtPathToSavedPhotosAlbum([outputFileURL absoluteString], self, #selector(video:didFinishSavingWithError:contextInfo:), nil);
}
else
{
NSLog(#"NO File is not compatible");
}
}
- (void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
if(! error)
{
NSLog(#"Video Saved to Album");
}
else
{
NSLog(#"Video not saved to Album - %#", [error description]);
}
NSError *er;
[[NSFileManager defaultManager] removeItemAtPath:OP_PATH error:&er];
if(! er)
{
NSLog(#"Temporary file deleted");
}
else
{
NSLog(#"Temporary file not deleted - %#", [er description]);
}
}
You are missing the following piece of code. See below
//Use timestamp to get new movie name everytime you capture
NSString *timeStamp = [NSString stringWithFormat:#"%0.0f",[[NSDate date] timeIntervalSince1970] * 1000];
NSString *movieOutputUrl =[NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.mov",timeStamp]];
NSURL *url = [NSURL URLWithString:movieOutputUrl];
[self.movieOutput startRecordingToOutputFileURL:url recordingDelegate:self];
I hope it helps.
Cheers.
- (void)captureOutput:(AVCaptureFileOutput *)captureOutputdidFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL fromConnections:(NSArray *)connections error:(NSError *)error
{
if (error)
{
NSLog(#"%#", error);
}
UIBackgroundTaskIdentifier backgroundRecordingID = [self backgroundRecordingID];
[self setBackgroundRecordingID:UIBackgroundTaskInvalid];
[[[ALAssetsLibrary alloc] init] writeVideoAtPathToSavedPhotosAlbum:outputFileURL completionBlock:^(NSURL *assetURL, NSError *error) {
if (error)
{
NSLog(#"%#", error);
}
[[NSFileManager defaultManager] removeItemAtURL:outputFileURL error:nil];
if (backgroundRecordingID != UIBackgroundTaskInvalid)
{
[[UIApplication sharedApplication] endBackgroundTask:backgroundRecordingID];
}
}];
}
Hope can help.

Change name at file in NSHomeDirectory

In my app, I store some image in NSHomeDirectory in this way:
NSString *jpgPath = [NSHomeDirectory() stringByAppendingPathComponent:[#"Documents/" stringByAppendingString:fileName]];
[UIImageJPEGRepresentation(image, 1.0) writeToFile:jpgPath atomically:YES];
I want to rename these file when I delete one of them
example:
I have in this directory
Photo1-Photo2-Photo3 the if I delete Photo 2 I want to rename Photo3 in Photo 2
How can I do it?
Based on the example, you seem to be trying to store the order of the photos. While you could try enumerating the directory and check which files need to be changed and then change them, It would probably be much easier to maintain the index of the images using a plist and read the mutable array object from it and delete the indexes that need to be deleted and their respective images. The order will be retained after deletion.
You would use the moveItemAtPath:toPath:error: method of a NSFileManager like so:
NSString *jpgPathOne = [NSHomeDirectory() stringByAppendingPathComponent:[#"Documents/" stringByAppendingString:#"Photo1.jpg"]];
NSString *jpgPathTwo = [NSHomeDirectory() stringByAppendingPathComponent:[#"Documents/" stringByAppendingString:#"Photo2.jpg"]];
NSString *jpgPathThree = [NSHomeDirectory() stringByAppendingPathComponent:[#"Documents/" stringByAppendingString:#"Photo3.jpg"]];
NSFileManager *localFileManager = [[NSFileManager alloc] init];
// ... delete Photo2
NSError *deleteError = nil;
BOOL deleted = [localFileManager removeItemAtPath:jpgPathTwo error:&deleteError];
if (!deleted || deleteError) {
NSLog(#"ERROR Deleting file: %#\n%# - %#", jpgPathTwo, [deleteError localizedDescription], [deleteError localizedFailureReason]);
} else {
// ... If delete worked, rename Photo3 to Photo2...
NSError *renameError = nil;
BOOL renamed = [localFileManager moveItemAtPath:jpgPathThree toPath:jpgPathTwo error:&renameError];
if (!renamed || renameError) {
NSLog(#"ERROR Moving file: %# to %#!\n%# - %#", jpgPathThree, jpgPathTwo, [renameError localizedDescription], [renameError localizedFailureReason]);
}
}
[localFileManager release];
This is untested, but it should work:
- (BOOL)deleteAndRename:(NSString *)filePath {
BOOL success = NO;
NSError *error = nil;
NSFileManager *fileManager = [[NSFileManager alloc] init];
if ([fileManager fileExistsAtPath:filePath]) {
success = [fileManager removeItemAtPath:filePath error:&error];
if (success) {
error = nil;
NSString *prevFilePath = filePath;
NSString *photoNumber = [[filePath stringByDeletingPathExtension] stringByReplacingOccurrencesOfString:#"Photo" withString:#""];
NSString *nextSequentialFile = [filePath stringByReplacingOccurrencesOfString:photoNumber withString:[NSString stringWithFormat:#"%d", ([photoNumber intValue] + 1)] options:NSBackwardsSearch range:NSRangeFromString(filePath)];
BOOL moveSuccess = NO;
while ([fileManager fileExistsAtPath:nextSequentialFile]) {
moveSuccess = [fileManager moveItemAtPath:nextSequentialFile toPath:prevFilePath error:&error];
if (moveSuccess) {
prevFilePath = nextSequentialFile;
photoNumber = [[prevFilePath stringByDeletingPathExtension] stringByReplacingOccurrencesOfString:#"Photo" withString:#""];
nextSequentialFile = [prevFilePath stringByReplacingOccurrencesOfString:photoNumber withString:[NSString stringWithFormat:#"%d", ([photoNumber intValue] + 1)] options:NSBackwardsSearch range:NSRangeFromString(prevFilePath)];
} else {
NSLog(#"*** Error Moving File: %# -> %# ***", nextSequentialFile, filePath);
if (error) {
NSLog(#"%# - %#", [error localizedDescription], [error localizedFailureReason]);
}
success = NO;
break;
}
}
success = moveSuccess;
} else {
NSLog(#"*** Error Deleting File: %# ***", filePath);
if (error) {
NSLog(#"%# - %#", [error localizedDescription], [error localizedFailureReason]);
}
}
} else {
NSLog(#"*** No such file: %# ***", filePath);
success = NO;
}
return success;
}

Resources