如何使用Asset url获取图像或视频文件的NSData

时间:2014-03-05 09:17:23

标签: ios

我有一个像

这样的网址
  

“资产库://asset/asset.PNG ID = 2B9DB56C-B9C6-4F4E-AD51-8A5E5F1DD2AA&安培; EXT = PNG”

在“images”数组中。我如何通过这个网址从媒体获取NSData? 我需要在此代码中使用NSData:

#pragma mark VK methods

+(NSMutableArray*)attachmentIds:(NSArray*)images forMe:(NSDictionary*)me{
    NSMutableArray *attachmentsList = [NSMutableArray new];

    for (int i = 0; i<images.count; i++){

        NSData *imageData = [NSData dataWithContentsOfURL:[images objectAtIndex:i] ];

        NSString *serverUrl = [self getServerForVKUploadPhotoToWall:me];
        NSDictionary *uploadResult = [self sendVKPOSTRequest:serverUrl withImageData:imageData];
        NSString *hash = [uploadResult objectForKey:@"hash"];
        NSString *photo = [uploadResult objectForKey:@"photo"];
        NSString *server = [uploadResult objectForKey:@"server"];
        NSString *attach_id = [self getVKAttachIdforUser:me photo:photo server:server hash:hash];
        [attachmentsList addObject:attach_id];
    }
    return attachmentsList;
}

但是NSData *imageData = [NSData dataWithContentsOfURL:[images objectAtIndex:i]]; 不起作用;

2 个答案:

答案 0 :(得分:2)

我解决了我的问题。谢谢https://www.cocoacontrols.com/controls/doimagepickercontroller

- (NSData *)getCroppedData:(NSURL *)urlMedia
{
    __block NSData *iData = nil;
    __block BOOL bBusy = YES;

    ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
    {
        ALAssetRepresentation *representation = myasset.defaultRepresentation;
        long long size = representation.size;
        NSMutableData *rawData = [[NSMutableData alloc] initWithCapacity:size];
        void *buffer = [rawData mutableBytes];
        [representation getBytes:buffer fromOffset:0 length:size error:nil];
        iData = [[NSData alloc] initWithBytes:buffer length:size];
        bBusy = NO;
    };

    ALAssetsLibraryAccessFailureBlock failureblock  = ^(NSError *myerror)
    {
        NSLog(@"booya, cant get image - %@",[myerror localizedDescription]);
    };

    [_assetsLibrary assetForURL:urlMedia
                    resultBlock:resultblock
                   failureBlock:failureblock];

    while (bBusy)
        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];

    return iData;
}

答案 1 :(得分:1)

我认为你可以看看question。这将允许您从给定的资产URL中检索UIImage,然后可以将其转换为NSData。

资产网址不是文件网址,因此dataWithContentsOfURL失败。