Can't save file to document folder

My iOS app sends a database to

WatchKit (watchOS 2)
. In
WatchKit
i use the following code to get the watch document folder to save the new file in:


- (void)session:(WCSession * _Nonnull)session

didReceiveFile:(WCSessionFile * _Nonnull)file

{

NSURL* url = [file fileURL];

NSURL* fileURL = [[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject] URLByAppendingPathComponent:@"MyDatabase.sqlite"];

// This results in an URL:

// @"file:///var/mobile/Containers/Data/PluginKitPlugin/47E13085-9030-4ED2-906F-01CBA323F07A/Documents/MyDatabase.sqlite"


// However, when I call the function:

[[NSFileManager defaultManager] replaceItemAtURL:fileURL withItemAtURL:url backupItemName:nil options:0 resultingItemURL:nil error:&error];

}


It throws an error saying:

Error Domain=NSCocoaErrorDomain Code=512 "The file “MyDatabase.sqlite” couldn’t be saved in the folder “Documents”." Error Domain=NSCocoaErrorDomain Code=513 "You don’t have permission to save the file “MyDatabase.sqlite”

How can I find a folder I'm allowed to save to? Naturally this code worked fine in the simulator so I assume I'm missing something.

BR Frederik

Replies

Could you try and see if a move works for you?


- (void)session:(WCSession * __nonnull)session didReceiveFile:(WCSessionFile * __nonnull)file
{
  NSError *error = nil;
  NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
  documentsPath = [documentsPath stringByAppendingPathComponent:@"MyDatabase.sqlite"];
  if ([[NSFileManager defaultManager] moveItemAtPath:[file.fileURL.path stringByExpandingTildeInPath] toPath:documentsPath error:&error]) {
     // success
  } else {
      NSLog(@"failed to move file: %@", error);
  }
}

I solved the problem by creating the URL through the following:


NSURL* fileURL = nil;
NSString *docPath = [NSHomeDirectory() stringByAppendingPathComponent:@"/Documents/"];
fileURL = [NSURL URLWithString:[docPath stringByAppendingPathComponent:@"CWPEntry.sqlite"]];


Thanks for the tip though!