“img”实际上是一个带有 URL 的字符串,但我实际上也将它用作文件名
NSString *applicationDocumentsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *storePath = [applicationDocumentsDir stringByAppendingPathComponent:img];
NSURL *url = [NSURL URLWithString:img];
NSData *imageData = [NSData dataWithContentsOfURL:url];
[imageData writeToFile:storePath atomically:TRUE];
在我的视图控制器中,我得到了这个:
UIImage *img = [[UIImage alloc] initWithContentsOfFile:self.initialImg];
if(img == nil) NSLog(@"image is nil");
[self.image setImage:img];
"initialImg" 是一个 NSString,其 url 与 "img" 中的相同。我还用另一个字符串(如 test.png)更改了“img”和“initialImg”,但这也不起作用。
它打印出“图像为零”,不知道为什么它是零......
编辑:
现在我得到了:
NSURL *url = [NSURL URLWithString:img];
NSData *imageData = [NSData dataWithContentsOfURL:url];
UIImage *uiImage=[UIImage imageWithData:imageData];
NSData *pngData = UIImagePNGRepresentation(uiImage);
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *filePath = [documentsPath stringByAppendingPathComponent:@"image.png"];
[pngData writeToFile:filePath atomically:YES];
在 viewDidLoad 函数的另一个视图控制器中:
UIImage *img = [[UIImage alloc] initWithContentsOfFile:@"image.png"];
if(img == nil) NSLog(@"image is nil");
[self.image setImage:img];
它仍然显示“图像为零”,我更改了网址,但它们是正确的