2013-08-25 42 views
2

我已经在iOS平台的版本0.20.x中看到了RestKit框架的很多重大更改。 目前我在网络上还没有找到的一件事是如何使用新版本的RestKit下载二进制文件的例子。使用RestKit 0.20.x下载二进制文件

我需要发送一个JSON对象到一个REST服务,并期望返回一个二进制文件。看起来很简单,不是吗,但由于某些原因,RestKit只希望JSON(以及常见的互联网内容类型,如XML)能够回来。 JSON对象本质上是一个请求对象,告诉服务应该去哪个图像并获取我的图像。

回答

7

幸运的是,我设法使用底层的AFNNetworking框架来帮助我,并利用RestKit序列化器生成我需要的请求对象。

MyRequestClass *request = // ... get my request class instance 
RKObjectManager *manager = [RKObjectManager sharedManager]; 
NSMutableURLRequest *downloadRequest = [manager requestWithObject:request method:RKRequestMethodPOST path:ROUTE_URL_MY_SERVICE parameters:nil]; 
AFHTTPRequestOperation *requestOperation = [[AFImageRequestOperation alloc] initWithRequest:downloadRequest]; 

[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 
    // Use my success callback with the binary data and MIME type string 
    callback(operation.responseData, operation.response.MIMEType, nil); 
} failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
    // Error callback 
    callback(nil, nil, error); 
}]; 
[manager.HTTPClient enqueueHTTPRequestOperation:requestOperation]; 
+0

最好的一段代码,我发现使用最新restkit下载一个简单的预览图像,谢谢:-) –

+0

我怎么能映射到MyResponseClass如果我收到一个JSON? – giuseppe

+0

这是为了发送JSON来接收二进制文件。如果您想将响应对象(以JSON形式)映射到类,则需要使用'RKObjectManager'来进行POST调用或任何其他操作,并让Restkit执行映射。 restkit网站有一些例子(https://github.com/RestKit/RestKit/)。 –