我有一个简单的方法来检查我是否传递了像“/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;
}
谢谢
最佳答案
问题在于如何访问 Assets 库 URL。这不是标准 URL,从 Assets 库 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;
}
关于ios - Objective-C/CocoaHTTPServer - 返回图像如何响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18505051/