0

我有这个简单的方法来检查我是否传递了像“/testPhoto”这样的参数,如果传递了,我想尝试用一个简单的图像来回答,该图像的路径可以在变量“testPath”中看到(静态尝试路径)。目前,当我发出请求时,我从服务器收到 200 ok 状态,但没有传递任何数据(0 字节)。我需要了解我做错了什么。也许 testPath 不包含正确的路径?我使用的路径是使用 ALAssetslibrary 找到的。

- (NSObject<HTTPResponse> *)httpResponseForMethod:(NSString *)method URI:(NSString *)path{

  HTTPLogTrace();

  if ([path isEqualToString:@"/testPhoto"]){
    NSString *testPath = [[NSString alloc] init];
    testPath = @"assets-library://asset/asset.JPG?id=DB96E240-8760-4FD6-B8B4-FEF3F61793B3&ext=JPG";
    NSURL *deviceImageUrl = [[NSURL alloc] initWithString:testPath];
    NSData *imageData = [NSData dataWithContentsOfURL:deviceImageUrl];
    UIImage *deviceImage = [UIImage imageWithData:imageData];

    HTTPDataResponse *photoResponse = [[HTTPDataResponse alloc] initWithData:imageData];
    return photoResponse;
  }

return nil;

}

谢谢

4

1 回答 1

1

问题在于您如何访问资产库 URL。这不是标准 URL,从资产库 URL 加载数据不能像这样工作。下面是一个例子:Getting NSData from an NSURL

下面的代码是基于上面的例子。我不是这方面的专家ALAssetLibrary,所以请谨慎尝试。它需要相当多的代码才能使资产库的异步工作再次同步:

- (NSObject<HTTPResponse> *)httpResponseForMethod:(NSString *)method URI:(NSString *)path{

    HTTPLogTrace();

    if ([path isEqualToString:@"/testPhoto"]){
        NSData* __block data = nil;

        dispatch_semaphore_t sema = dispatch_semaphore_create(0);
        dispatch_queue_t queue = dispatch_get_main_queue();

        ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
        {
            ALAssetRepresentation *rep;
            if([myasset defaultRepresentation] == nil) {
                return;
            } else {
                rep = [myasset defaultRepresentation];
            }
            CGImageRef iref = [rep fullResolutionImage];

            dispatch_sync(queue, ^{
                UIImage *myImage = [UIImage imageWithCGImage:iref];
                *data = UIImageJPEGRepresentation(myImage, 1);
            });

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

            dispatch_semaphore_signal(sema);
        };

        NSString *testPath = @"assets-library://asset/asset.JPG?id=DB96E240-8760-4FD6-B8B4-FEF3F61793B3&ext=JPG";
        NSURL *deviceImageUrl = [[NSURL alloc] initWithString:testPath];
        ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init]; //usin ARC , you have to declare ALAssetsLibrary as member variable
        [assetslibrary assetForURL:deviceImageUrl
                       resultBlock:resultblock
                      failureBlock:failureblock];

        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);

        dispatch_release(sema);


        HTTPDataResponse *photoResponse = [[HTTPDataResponse alloc] initWithData:imageData];
        return photoResponse;
    }
    return nil;
}
于 2013-08-29T07:58:13.343 回答