无法从 iPhone 设备文件夹获取图像
我正在尝试从设备(iPhone)获取一些图像并将其显示在屏幕上。
图像文件保存在我的设备上,并分隔在如下文件夹中:(...)/Documents/1/image1.png。
这是我尝试获取图像的函数的代码
-(UIImage *) getImageFromDevice:(NSString *) fileName
idImage:(int) idImage{
NSString *path;
path = [[self dataFilePath] stringByAppendingString:@"/"];
path = [path stringByAppendingString: [[NSString alloc] initWithFormat:@"%d",idImage]];
path = [path stringByAppendingString:@"/"];
path = [path stringByAppendingString:fileName];
NSLog(@"path = %@", path);
NSURL *deviceImageUrl = [[NSURL alloc] initWithString:path];
NSData *imageData = [NSData dataWithContentsOfURL:deviceImageUrl];
UIImage *deviceImage = [UIImage imageWithData:imageData];
return deviceImage;
}
,这是获取工作正常的设备文件夹路径的函数:
-(NSString *)dataFilePath{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return documentsDirectory;
}
但是当我使用<设置NSURL *deviceImageUrl时strong>[[NSURL alloc] initWithString:path] deviceImageUrl 变为nil。
我做错了什么?
I'm trying to get some images from the device (iPhone) and show them on screen.
The image files are saved on my device and separated in folders like this: (...)/Documents/1/image1.png.
Here is the code of the function where I'm trying to get the image
-(UIImage *) getImageFromDevice:(NSString *) fileName
idImage:(int) idImage{
NSString *path;
path = [[self dataFilePath] stringByAppendingString:@"/"];
path = [path stringByAppendingString: [[NSString alloc] initWithFormat:@"%d",idImage]];
path = [path stringByAppendingString:@"/"];
path = [path stringByAppendingString:fileName];
NSLog(@"path = %@", path);
NSURL *deviceImageUrl = [[NSURL alloc] initWithString:path];
NSData *imageData = [NSData dataWithContentsOfURL:deviceImageUrl];
UIImage *deviceImage = [UIImage imageWithData:imageData];
return deviceImage;
}
And this is the function to get the path to the device folder that's working fine:
-(NSString *)dataFilePath{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return documentsDirectory;
}
But when I set the NSURL *deviceImageUrl with [[NSURL alloc] initWithString:path] the deviceImageUrl becomes nil.
What I'm doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试使用 fileURLWithPath: 而不是 URLWithString: ;)
我也总是搞乱这两种方法......它们让我发疯。
Try using fileURLWithPath: instead of URLWithString: ;)
I always mess up with these two methods, too ... they're making me crazy.
您不应使用 initWithString: ,这必须符合 RFC 中描述的 URL 格式。如果你只想使用系统路径,请使用这个:(使用后不要忘记释放)
You should not use initWithString: , this must conform to URL format as described in RFCs. If you just want to use a system path, use this : (don't forget to release after use it)