Vincenzo Putignano
Vincenzo Putignano

Reputation: 153

iOS - copy file after open in my app

after clicked open in (pdf file) with this code:

-(BOOL)application:(UIApplication *)application
       openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
    annotation:(id)annotation {
if (url != nil && [url isFileURL]) {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSFileManager *filemgr;
    NSError *erf;
    filemgr = [NSFileManager defaultManager];
    if ([filemgr copyItemAtPath:[NSString stringWithFormat:@"%@", url] toPath:documentsDirectory error: &erf]  == YES)
        NSLog (@"Copy successful");
    else
        NSLog (@"Copy failed%@dest: %@", erf, url);
}
return YES;

}

I want copy file to my app but i have this error:

Error Domain=NSCocoaErrorDomain Code=260 "The operation couldn’t be completed. (Cocoa error 260.)" UserInfo=0x200826c0 {NSFilePath=file://localhost/private/var/mobile/Applications/*.pdf, NSUnderlyingError=0x20082510 "The operation couldn’t be completed. No such file or directory"} Whi?

Upvotes: 1

Views: 1231

Answers (2)

Michael
Michael

Reputation: 1213

You probably want to think about moving that onto a background queue/thread because you are essentially locking up your app when it's called. This has two major side effects

  1. Your app will appear to have hung during the copy operation, which will not be great for the user experience.
  2. If it takes too long to do the copy, the app will not be able to respond to the OS and so the OS will think the app has hung forever and will kill it.

I would write a new method that takes a URL for copying and then you can do some unit testing against that method to make sure it's solid, before then scheduling it onto a queue/background thread in your application:openURL:sourceApplication:annotation:

Upvotes: 0

rmaddy
rmaddy

Reputation: 318924

You can't convert an NSURL representing a file URL to an NSString using stringWithFormat:. You need to call the path method on the NSURL. And the toPath: parameter needs to be a full path including filename, not just the directory your want to copy to.

NSString *sourcePath = [url path];
NSString *destPath = [documentsDirectory stringByAppendingPathComponent:[url lastPathComponent]];

if ([filemgr copyItemAtPath:sourcePath toPath:destPath error:&erf]) {

Upvotes: 1

Related Questions