为什么我的文件没有保存?

时间:2011-09-11 13:41:00

标签: iphone objective-c ios xcode save

我正在使用一些代码来保存UIWebView中的png文件。它没有工作,按下“保存”按钮时没有任何反应。除了“保存文件...”之外,日志中没有任何内容出现,只是为了测试它是否正确地在Interface Builder中链接(它是)。

这是我正在使用的代码:

-(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]; 
    } 
} 

1 个答案:

答案 0 :(得分:4)

似乎你试图写入mainBundle的文件位置(设备上不允许/不可能)。尝试使用

查找文档目录
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
NSUserDomainMask, YES); 
NSString* resourceDocPath = [paths objectAtIndex:0];