简体   繁体   中英

Why isn't my file saving?

I am using some code to save a png file from UIWebView. It isn't working and nothing happens when the "save" button is pressed. Nothing appears in the log, apart from "Saving File..." which is just to test that it's all linked up in the Interface Builder correctly (which it is).

Here's the code I am using:

-(IBAction)saveFile 
{ 

NSLog(@"Saving File...");

NSURL *requestedURL = [webView.request URL]; 

if([[requestedURL pathExtension] isEqualToString:@"png"]) 
{ 
    NSData *fileData = [[NSData alloc] initWithContentsOfURL:requestedURL]; 
    //Store the data locally 
    NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle] resourcePath]     
stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"Documents"]]; 

    NSString *filePath = [resourceDocPath stringByAppendingPathComponent:[requestedURL lastPathComponent]]; 

    NSError *error = nil; 
    [fileData writeToFile:filePath options:NSDataWritingFileProtectionComplete error:&error]; 

    if(error != nil) { 
        // Failed to write the file 
        NSLog(@"Failed to write file: %@", [error description]); 
    } else { 
        UIAlertView *filenameAlert = [[UIAlertView alloc] initWithTitle:@"File saved" message:[NSString  
stringWithFormat:@"The file %@ has been saved", [requestedURL lastPathComponent]] delegate:self cancelButtonTitle:@"OK" 
otherButtonTitles:nil]; 

        [filenameAlert show]; 
        [filenameAlert release]; 
    } 
} 

Seems you try to write to the file location of the mainBundle (which is not allowed/possible on the device). Try to lookup the documents directory using

NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
NSUserDomainMask, YES); 
NSString* resourceDocPath = [paths objectAtIndex:0]; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM