Objective-C / CocoaHTTPServer - 返回图像如何响应

时间:2013-08-29 07:46:03

标签: ios objective-c cocoahttpserver

我有这个简单的方法,检查我是否传递了像“/ 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;

}

由于

1 个答案:

答案 0 :(得分: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;
}