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;
}
Related
Given a url like this:
file:///private/var/mobile/Applications/C133BAE7-0CBC-4E4F-826B-509B5E1EB68E/tmp/uzhMyDkL0mSI-SCVideo-Merged.mov
How can I get the NSData representation of this to send to a server? I've tried all of these:
NSData *videoData = [NSData dataWithContentsOfURL:url];
NSData *videoData = [NSData dataWithContentsOfFile:[url absoluteString]];
NSData *videoData = [[NSFileManager defaultManager] contentsAtPath:[url path]];
videoData is nil every time.
EDIT:
For more context I am trying to use SCRecorder to capture video.
- (void)recorder:(SCRecorder *__nonnull)recorder didCompleteSegment:(SCRecordSessionSegment *__nullable)segment inSession:(SCRecordSession *__nonnull)session error:(NSError *__nullable)error {
[session mergeSegmentsUsingPreset:AVAssetExportPresetHighestQuality completionHandler:^(NSURL *url, NSError *error) {
if (error == nil) {
//NSData *videoData = [NSData dataWithContentsOfURL:url];
//NSData *videoData = [NSData dataWithContentsOfFile:[url absoluteString]];
NSData *videoData = [[NSFileManager defaultManager] contentsAtPath:[url path]];
} else {
NSLog(#"Bad things happened: %#", error);
}
}];
}
The file URL looks correct to me but to be really sure, you should add in this method before trying to fetch NSData:
NSError *error = nil;
if ([url checkResourceIsReachableAndReturnError: &error] == FALSE)
{
NSLog(#"URL %# is not available because %#", [url absoluteString], [error localizedDescription]);
}
You can also try fetching the file via:
NSError *error = nil;
NSData *videoData = [NSData dataWithContentsOfURL:url
options: NSDataReadingUncached
error:&error];
if (videoData == nil)
{
NSLog(#"URL %# is not available because %#", [url absoluteString], [error localizedDescription]);
} else {
// you've likely got data, since videoData is not nil!
}
This is weird, but it works if I do this:
- (void)recorder:(SCRecorder *__nonnull)recorder didCompleteSegment:(SCRecordSessionSegment *__nullable)segment inSession:(SCRecordSession *__nonnull)session error:(NSError *__nullable)error {
[session mergeSegmentsUsingPreset:AVAssetExportPresetHighestQuality completionHandler:^(NSURL *url, NSError *error) {
if (error == nil) {
[self getDataFromUrl:url];
} else {
NSLog(#"Bad things happened: %#", error);
}
}];
}
- (void)getDataFromUrl:(NSURL *)url {
NSError *error = nil;
NSData *videoData = [NSData dataWithContentsOfURL:url
options:NSDataReadingUncached
error:&error];
if (videoData == nil)
{
NSLog(#"URL %# is not available because %#", [url absoluteString], [error localizedDescription]);
} else {
NSLog(#"GOT IT");
}
}
videoData is now valid NSData. Any explanation on why this works if separated into a different method?
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];
}
My app had been rejected the 2nd times and I lost 3 weeks :(
The first submit, I excluded ONLY DIRECTORIES from being backed-up in iCloud. Apple rejected...
The second submit, I excluded DIRECTORIES & PICTURES downloaded from being backed-up in iCloud. Apple again rejected... Apple also complaint that I have no "Restore" feature for my In-App purchase, while in fact, I do have a "Restore" button and it worked when I tested it.
I've done as Apple had suggested by excluding the file from being backedup using NSURLIsExcludedFromBackupKey. There was an interesting comment made by Macmade's on stackoverflow here:
sometimes Apple reviewers think your data can be re-generated, when
it's not. Then you'll have to explain why the data has to be backed-up
How often do the reviewer misunderstood and we have to explain to them that the content is required offline & not re-generateable?
Here is the code I used to exclude my files & directories from iCloud. Do you spot any problems?
- (BOOL)addSkipBackupAttributeToItemAtURL:(NSURL *)URL
{
// There's a chance the download failed, but don't assert here
//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;
}
//Download picture from Google and exclude it from being backed-up in iCloud
- (void)downloadFetcher:(GTMHTTPFetcher *)fetcher
finishedWithData:(NSData *)data
error:(NSError *)error
{
if (error == nil) {
// successfully retrieved this photo's data; save it to disk
GDataEntryPhoto *photoEntry = [fetcher propertyForKey:#"photo entry"];
// Create album directory if it doesn't already exist
NSString *path = [self findOrCreateApplicationSupportSubPath:[photoEntry albumTitle]];
path = [path stringByAppendingPathComponent:[[photoEntry title] stringValue]];
if (path != nil) {
// Write to disk
BOOL didSave = [data writeToFile:path
options:NSDataWritingAtomic
error:&error];
if (didSave) {
// Exclude file from being backed up in iCloud
NSURL *url = [NSURL fileURLWithPath:path];
BOOL excludeBackupResult = [self addSkipBackupAttributeToItemAtURL:url];
if (excludeBackupResult == NO) {
NSLog(#"Error excluding FILE from iCloud: %#", path);
}
// Update the download progress bar
_downloadedFileCounter = _downloadedFileCounter + 1;
float progress = _downloadedFileCounter / kMaleWireframeImagesTotal;
[self updateProgress:progress];
// The download completed. -2 just incase a package is lost, but let the user move on...
if (_downloadedFileCounter >= _downloadableFilesTotal -2) {
[_panel6 downloadCompleted];
}
} else {
// error saving file. Perhaps out of space? Write permissions error?
NSLog(#"Save anatomy picture failed: %#", error.localizedDescription);
}
} else {
NSLog(#"downloadFetcher: Cannot create directory");
}
} else {
NSLog(#"downloadFetcher failed: %#", error);
}
}
//Create directory and exclude it from being backed-up in iCloud
-(NSString*)findOrCreateApplicationSupportSubPath:(NSString*)subPath
{
NSString *resolvedPath;
NSArray *appSupportDir = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
if ([appSupportDir count] != 0) {
resolvedPath = [appSupportDir objectAtIndex:0];
// Append the name of this application
NSString *executableName = [[[NSBundle mainBundle] infoDictionary] objectForKey:#"CFBundleExecutable"];
resolvedPath = [resolvedPath stringByAppendingPathComponent:executableName];
resolvedPath = [resolvedPath stringByAppendingPathComponent:subPath];
NSFileManager *manager = [NSFileManager defaultManager];
if (![manager fileExistsAtPath:resolvedPath]) {
// Path doesn't exist, creates it
NSError *error;
BOOL successful = [manager createDirectoryAtPath:resolvedPath withIntermediateDirectories:YES attributes:nil error:&error];
if(!successful) {
NSLog(#"ERROR creating APP Support Sub-Directory: %#", error.localizedDescription);
return nil;
} else {
// Exclude path from backing-up in iCloud
NSURL *url = [NSURL fileURLWithPath:resolvedPath];
BOOL excludeBackupResult = [self addSkipBackupAttributeToItemAtURL:url];
if(!excludeBackupResult){
NSLog(#"Error excluding DIRECTORY from iCloud backup. This is a violation to their guideline.");
return nil;
}
}
}
} else {
NSLog(#"No Application Support Path available");
return nil;
}
return resolvedPath;
}
I think the trick is to add the NSURLIsExcludedFromBackupKey OR make sure the directory is outside the documents directory. I did this by moving my documents to the Library/Application Support folder (since it didn't make sense in the /tmp or /Caches folders):
- (void)createNewRefFolder
{
NSError *error;
// store in /Library/Application Support/BUNDLE_IDENTIFIER/Reference
// make sure Application Support folder exists
NSURL *applicationSupportDirectory = [[NSFileManager defaultManager] URLForDirectory:NSApplicationSupportDirectory
inDomain:NSUserDomainMask
appropriateForURL:nil
create:YES
error:&error];
if (error) {
NSLog(#"KCDM: Could not create application support directory. %#", error);
}
NSURL *referenceFolder = [applicationSupportDirectory URLByAppendingPathComponent:#"Reference" isDirectory:YES];
if (![[NSFileManager defaultManager] createDirectoryAtPath:[referenceFolder path]
withIntermediateDirectories:YES
attributes:nil
error:&error]) {
NSLog(#"KCDM: Error creating Reference folder: %# ...", error);
}
BOOL success = [referenceFolder setResourceValue:#YES forKey: NSURLIsExcludedFromBackupKey error: &error];
if(!success){
NSLog(#"KCDM: Error excluding %# from backup %#", referenceFolder, error);
}
}
Little UPDATE from previous answers.
You have to check the existence of the file. Otherwise, you will get this error,
Error excluding [FileName] from backup:
Error Domain=NSCocoaErrorDomain Code=4 "The file “[FileName]” doesn’t exist."
...
I am not sure if we should check for the value is already updated or not.
e.g. if the API reset already set value or not. If it tries to update the file system again for a set value that is more time consuming, I guess.
Updated method...
+ (BOOL)addSkipBackupAttributeToURLAtPath:(NSURL *)url
{
if (!url) return NO;
if (![[NSFileManager defaultManager] fileExistsAtPath:url.path]) return NO;
NSError *error = nil;
NSNumber *value = nil;
BOOL success = [url getResourceValue:&value forKey:NSURLIsExcludedFromBackupKey error:&error];
if (value.boolValue == YES) return YES;
success = [url setResourceValue:[NSNumber numberWithBool:YES]
forKey:NSURLIsExcludedFromBackupKey error:&error];
if(!success){
NSLog(#"Error excluding %# from backup: %#", [url lastPathComponent], error);
}
return success;
}
+ (BOOL)addSkipBackupAttributeToFileAtPath:(NSString *)path
{
if (!path) return NO;
return [self addSkipBackupAttributeToURLAtPath:[NSURL fileURLWithPath:path]];
}
I come across a problem, every time I try to get the SQLite file using documentDirectory, I just could not find it. I really wonder where the SQLite file is put in the project file and how I can get the name of it so that I can find the SQLite file.
- (void) save
{
// Create UIManagedDocument
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *documentDirectory = [[fileManager URLsForDirectory:NSDocumentationDirectory inDomains:NSUserDomainMask]firstObject];
NSString *documentName = #"Model";
NSURL *url = [documentDirectory URLByAppendingPathComponent:documentName];
UIManagedDocument *document = [[UIManagedDocument alloc]initWithFileURL:url];
if ([fileManager fileExistsAtPath:[url path]]) {
[document openWithCompletionHandler:^(BOOL success) {
if (success) {
if (document.documentState == UIDocumentStateNormal) {
// Get a ManagedObjectContext
NSManagedObjectContext *context = document.managedObjectContext;
// Set managed object (entity)
NSManagedObject *aPerson = [NSEntityDescription insertNewObjectForEntityForName:#"Person" inManagedObjectContext:context];
// Set value for the attribute (which are "name" and "age") of the entity
[aPerson setValue:self.nameTextField.text forKey:#"name"];
[aPerson setValue:self.ageTextField.text forKey:#"age"];
// Check whether there is an error
NSError *error = nil;
if (![context save:&error]) {
NSLog(#"Can't save due to %#%#", error, [error localizedDescription]);
}
// Close the window
[self dismissViewControllerAnimated:YES completion:nil];
}
}
if (!success) {
NSLog(#"couldn't open document at %#", url);
}
}];
}
else {
[document saveToURL:url forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {
if (success) {
if (document.documentState == UIDocumentStateNormal) {
// Get a ManagedObjectContext
NSManagedObjectContext *context = document.managedObjectContext;
// Set managed object (entity)
NSManagedObject *aPerson = [NSEntityDescription insertNewObjectForEntityForName:#"Person" inManagedObjectContext:context];
// Set value for the attribute (which are "name" and "age") of the entity
[aPerson setValue:self.nameTextField.text forKey:#"name"];
[aPerson setValue:self.ageTextField.text forKey:#"age"];
// Check whether there is an error
NSError *error = nil;
if (![context save:&error]) {
NSLog(#"Can't save due to %#%#", error, [error localizedDescription]);
}
// Close the window
[self dismissViewControllerAnimated:YES completion:nil];
}
}
if (!success) {
NSLog(#"couldn't open document at %#", url);
}
}];
}
}
Every time when I run the apps, the debugger will say that:
2014-07-29 15:41:22.476 TableAndCoreData[2502:60b] couldn't open document at file:///Users/Mike/Library/Application%20Support/iPhone%20Simulator/7.1/Applications/DB1F0215-2BF2-43B5-ADF2-76ABC9E2CD16/Library/Documentation/Model
try this instead:
NSURL *documentDirectory = [[fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask]firstObject];
I'm having trouble synching a simple textfile, I get this error when trying to open it:
{NSFilePath=/private/var/mobile/Library/Mobile Documents/4C224W52W5~com~piso13~opusDomini/currentLogPath, NSUnderlyingError=0xde9b460 "The operation couldn’t be completed. Bad file descriptor"}
This is how I create it
-(BOOL)createLogFolderFile{
NSString *uuid = nil;
CFUUIDRef uuidRef = CFUUIDCreate(nil);
uuid = (NSString*)CFUUIDCreateString(nil, uuidRef);
CFRelease(uuidRef);
NSError *error = nil;
[uuid writeToFile:[self filePath] atomically:NO encoding:NSUTF8StringEncoding error:&error];
if (error) {
NSLog(#"Error trying to create log file %#", error);
return FALSE;
}
else{
return TRUE;
}
}
-(NSString*)filePath{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *iCloudPath = [[fileManager URLForUbiquityContainerIdentifier:nil] path];
return [iCloudPath stringByAppendingPathComponent:LOG_FOLDER_FILE_NAME];
}
This is how I read it:
-(NSString*)readLogFolderFromFile{
NSError *error = nil;
NSString *logFolder = [NSString stringWithContentsOfFile:[self filePath] encoding:NSUTF8StringEncoding error:&error];
if (error) {
NSLog(#"Error when trying to read log folder from file: %#" ,error);
return nil;
}
else{
return logFolder;
}
}
I'm using NSMetadataQuery to search for the file,
The notification query finish gathering info results positive.
Help?
The file was not downloaded. It seems NSMetadataQuery notifies about the existence of the file in the cloud. To actually get the file, extra code is needed:
Inside queryDidFinishGathering notification:
NSMetadataItem *item = [query resultAtIndex:0];
self.metadataItem = item;
BOOL isDownloaded = [[item valueForAttribute:NSMetadataUbiquitousItemIsDownloadedKey]boolValue];
if (!isDownloaded) {
NSError *error = nil;
[[NSFileManager defaultManager] startDownloadingUbiquitousItemAtURL: [item valueForAttribute:NSMetadataItemURLKey] error:&error];
NSLog(#"Start downloading file");
if (error) {
NSLog(#"Error trying to download file: %#", error);
}
else{
[self lookForLogFolderFile];
return;
}
}
The lookForLogFolderFile simply starts the query again.
After several calls my item gets downloaded. You can also use a timer to between each call to start a NSMetadataQuery. In my case, is just a text file with one line.