【问题标题】:Loading UIImage from UIImagePickerControllerReferenceURL从 UIImagePickerControllerReferenceURL 加载 UIImage
【发布时间】:2012-06-14 22:20:18
【问题描述】:

我正在使用 UIImagePickerController 来允许用户从图像库中选择图像。然后我想在 sqlite 数据库中启动该文件的位置,以便以后可以参考它。

我一直在谷歌上搜索如何做到这一点,但我发现的很短。我知道我可以通过在委托方法中调用来获取项目的 ReferenceURL:

    NSURL *picURL = [info objectForKey:@"UIImagePickerControllerReferenceURL"]

这确实给了我一个有效的 NSURL 对象,如果我输出 picURL.absoluteString,我可以看到文件资产库位置的有效 url。但是,如果我尝试使用此 url 创建一个 NSData 对象,以便我可以反过来创建一个 UIImage,代码将失败,因为 NSData 返回 nil。例如:

    NSURL *picURL = [info objectForKey:@"UIImagePickerControllerReferenceURL"]
    NSString *stringUrl = picURL.absoluteString;
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:stringUrl]];
    imgMain.image = [UIImage imageWithData:data]

我意识到我在这里有些重复,但重点是获取我可以存储在 sqlite 中的 URL 的字符串表示形式,然后稍后使用该字符串创建图像(所以上面的代码代表了这种思路)。

我发现了一些关于使用 ALAssetsLibrary 的信息,但这给了我各种各样的配合,因为它似乎不适用于 iOS 5 和 ARC。我不断收到错误消息“例如,接收器类型 ALAsset 消息是前向声明。我可以在引用 ALAsset / ALAssetsLibrary 的文件上设置属性以忽略 ARC,这会停止构建错误,但是一旦我离开代码块,数据就会消失。见下文:

    NSURL *referenceURL = [info objectForKey:UIImagePickerControllerReferenceURL];
    ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
    __block UIImage *returnValue = nil;
    [library assetForURL:referenceURL resultBlock:^(ALAsset *asset) {
        returnValue = [UIImage imageWithCGImage:[[asset defaultRepresentation] fullResolutionImage]];
    } failureBlock:^(NSError *error) {
       // error handling
    }];
    [library release];

returnValue 确实返回了一个有效的图像,但只要代码退出 resultBlock,数据的内容就会消失(即 returnValue 再次变为 null)。

所以我的问题是:如何使用 UIImagePickerControllerReferenceURL 并将其转换为可以存储在 sqlite 中的字符串,然后使用该字符串在以后创建有效的 UIImage 对象?

【问题讨论】:

  • 你对 thsi 有什么收获吗?

标签: objective-c ios uiimage uiimagepickercontroller


【解决方案1】:

看起来你在正确的轨道上,保存资产网址。

Save
NSURL *picURL = [info objectForKey:@"UIImagePickerControllerReferenceURL"]
NSString *stringUrl = picURL.absoluteString;


Reload AssetURL
NSURL asssetURL = [NSURL URLWithString:stringUrl]

至于稍后加载资产,我将基于您不使用 arc 的假设。这可以解释为什么你的 returnValue 为零。

您是否尝试在结果中添加保留?例如:

    NSURL *referenceURL = [NSURL URLWithString:savedAssetURLString]
    ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
    __block UIImage *returnValue = nil;
    [library assetForURL:referenceURL resultBlock:^(ALAsset *asset) {
        returnValue = [[UIImage imageWithCGImage:[[asset defaultRepresentation] fullResolutionImage]] retain]; //Retain Added
    } failureBlock:^(NSError *error) {
       // error handling
    }];
    [library release];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-15
    • 1970-01-01
    • 1970-01-01
    • 2012-06-30
    • 2013-08-27
    • 2012-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多