【问题标题】:Why isn't my file saving?为什么我的文件没有保存?
【发布时间】:2011-11-14 18:26:21
【问题描述】:

我正在使用一些代码从 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]; 
    } 
} 

【问题讨论】:

  • 您可能没有正确构建resourceDocPath 路径。我通常使用这个:#define _docs [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]

标签: iphone objective-c ios xcode save


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-30
    • 1970-01-01
    • 2013-09-23
    相关资源
    最近更新 更多