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



我有一个简单的方法,可以检查我是否传递了一个像"/testPhoto"这样的参数,如果传递了,我想尝试用一个简单图像来回答,该图像的路径可以在变量"testPath"中看到(静态路径表示try)。目前,当我进行请求时,我从服务器接收到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;
}

感谢

问题在于如何访问资产库URL。这不是一个标准的URL,从资产库URL加载数据不会像这样工作。以下是如何做到这一点的示例:从NSURL 获取NSData

以下代码基于上述示例。我不是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;
}

相关内容

  • 没有找到相关文章

最新更新