我正在使用一些代码来保存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];
}
}
答案 0 :(得分:4)
似乎你试图写入mainBundle的文件位置(设备上不允许/不可能)。尝试使用
查找文档目录NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString* resourceDocPath = [paths objectAtIndex:0];