gpt4 book ai didi

ios - 错误 : The file. ..在 imageData 上调用 writeToFile 时不存在

转载 作者:IT王子 更新时间:2023-10-29 08:21:52 25 4
gpt4 key购买 nike

我正在尝试在 NSURLSessionDownloadTask 的完成 block 中使用以下代码将数据写入文件:

   void (^completionBlock)(NSURLResponse *response, NSURL *filePath, NSError *error) = ^void (NSURLResponse *response, NSURL *filePath, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
if (!error){
NSData *imageData = [NSData dataWithContentsOfURL:filePath];
if(imageData) NSLog(@"image is not null");

if(pic == 1) self.imageView.image = [UIImage imageWithData:imageData];
else if(pic==2) self.imageView2.image = [UIImage imageWithData:imageData];

NSArray *paths = [[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];
NSURL *documentsDirectoryURL = [paths lastObject];
NSURL *saveLocation;
if(pic == 1) saveLocation = [documentsDirectoryURL URLByAppendingPathComponent:self.pictureName1];
else if (pic == 2) saveLocation = [documentsDirectoryURL URLByAppendingPathComponent:self.pictureName2];
else saveLocation = [documentsDirectoryURL URLByAppendingPathComponent:self.pictureName3];

NSLog(@"for # %d writing to file %@", pic, saveLocation);

NSError *error = nil;
[imageData writeToFile:[saveLocation absoluteString] options:NSAtomicWrite error: &error];
if(error){
NSLog(@"FAILED\n\n\n %@ \n\n\n", [error description]);
}
}

我能够在 UIImageViews 中显示下载的图像,并且我对 imageData 的空检查同样确认它不为空。但是,当我尝试将数据写入文件时,我的 NSLog 打印出以下错误,表明写入失败:

(log statements)
# 3 writing to file file:///var/mobile/Containers/Data/Application/3743A163-7EE1-4A5A-BF81-7D1344D6DA45/Documents/pic3.png
Error Domain=NSCocoaErrorDomain Code=4 "The file “pic1.jpg” doesn’t exist."
UserInfo={NSFilePath=file:///var/mobile/Containers/Data/Application/3743A163-7EE1-
4A5A-BF81-7D1344D6DA45/Documents/pic1.jpg, NSUnderlyingError=0x16d67200 {Error
Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}

我没能在 SO 上找到另一个问题,指出此文件的此错误消息,而且我发现错误消息非常违反直觉。我的错误在哪里?

最佳答案

使用 [saveLocation path] 代替 [saveLocation absoluteString]。基本上前者给你“file:///path/filename”,而后者给你“/path/filename”,这是正确的格式。

关于ios - 错误 : The file. ..在 imageData 上调用 writeToFile 时不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32716895/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com