gpt4 book ai didi

iphone - 如何在 Objective-c 中将文件保存在应用程序的资源文件夹中

转载 作者:太空狗 更新时间:2023-10-30 03:49:06 25 4
gpt4 key购买 nike

我正在用 objective-c 为 iphone 开发一个应用程序。我的问题是我的应用程序必须保存从 url 获取的图像。我认为该文件夹是只读的。这是我保存图像的代码:

-(void)banner:(NSString *)path{
NSData * imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: path]];
UIImage *image = [UIImage imageWithData: imageData];
NSString* resourcePath = [[NSBundle mainBundle] resourcePath];
NSString* pathEnd = [resourcePath stringByAppendingFormat:@"/banner.png"];
NSData *data1 = [NSData dataWithData:UIImagePNGRepresentation(image)];
NSError *writeError = nil;
[data1 writeToFile:pathEnd options:NSDataWritingAtomic error:&writeError];
}

但是当我检索图像时,它不在那个文件夹中。我能做什么?

最佳答案

你不能,应用程序包是只读的。您应该将任何数据保存在文档或缓存目录中。

-(void)banner:(NSString *)path{
NSData * imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: path]];
UIImage *image = [UIImage imageWithData: imageData];

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"banner.png"];

NSData *data1 = [NSData dataWithData:UIImagePNGRepresentation(image)];
NSError *writeError = nil;

[data1 writeToFile:filePath options:NSDataWritingAtomic error:&writeError];

if (writeError) {
NSLog(@"Error writing file: %@", writeError);
}
}

是否有任何理由先将数据转换为图像,然后再次转换回 NSData 对象?

如果没有,你可以这样做:

-(void)banner:(NSString *)path{
NSData * imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: path]];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);         NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"banner.png"];
NSError *writeError = nil;
[imageData writeToFile:filePath options:NSDataWritingAtomic error:&writeError];

if (writeError) {
NSLog(@"Error writing file: %@", writeError);
}
}

关于iphone - 如何在 Objective-c 中将文件保存在应用程序的资源文件夹中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8122912/

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