【问题标题】:AFNetworking - Download File, unexpected message format 'Raw'AFNetworking - 下载文件,意外消息格式“原始”
【发布时间】:2013-10-17 19:46:48
【问题描述】:

我基本上是在尝试下载一个可以从 PDF 到 PNG 的文件。我正在使用 AFNetworking 1.x。

但是,我收到一个错误:

NSURL *baseURL = [NSURL URLWithString:@"https://myserver.com/webservices/Services/"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:baseURL];
//NSLog(@"Formatted URL: %@", formattedURL);
//NSMutableURLRequest *photoRequest = [NSMutableURLRequest requestWithURL:url];
NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];
[httpClient defaultValueForHeader:@"Accept"];
[httpClient setParameterEncoding:AFFormURLParameterEncoding];

[parameters setObject:[NSNumber numberWithInteger:@"10772"] forKey:@"FileId"];
[parameters setObject:[NSNumber numberWithBool:YES] forKey:@"requireUnCompression"];
NSMutableURLRequest *fileRequest = [httpClient requestWithMethod:@"POST" path:@"FileService.svc/DownloadFile" parameters:parameters];
//[fileRequest setHTTPBody:<#(NSData *)#>]
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:fileRequest];

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"Successss!");
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Failed: %@", [operation error]);
}];

[httpClient enqueueHTTPRequestOperation:operation];

但是,我收到一个错误:

Failed: Error Domain=AFNetworkingErrorDomain Code=-1011 "Expected status code in (200-299), got 400" UserInfo=0x12112770 {NSLocalizedRecoverySuggestion={"faultType":"InvalidOperationException","message":"The incoming message has an unexpected message format 'Raw'. The expected message formats for the operation are 'Xml', 'Json'. This can be because a WebContentTypeMapper has not been configured on the binding. See the documentation of WebContentTypeMapper for more details."}, AFNetworkingOperationFailingURLRequestErrorKey=<NSMutableURLRequest: 0xc865c40> { URL: https://myserver.com/webservice/Services/FileService.svc/DownloadFile }, NSErrorFailingURLKey=https://myserver.com/webservices/Services/FileService.svc/DownloadFile, NSLocalizedDescription=Expected status code in (200-299), got 400, AFNetworkingOperationFailingURLResponseErrorKey=<NSHTTPURLResponse: 0xc8696a0> { URL: https://myserver.com/webservices/Services/FileService.svc/DownloadFile } { status code: 400, headers { "Cache-Control" = private; "Content-Length" = 327; "Content-Type" = "application/xml; charset=utf-8"; Date = "Thu, 17 Oct 2013 19:45:07 GMT"; "Persistent-Auth" = true; Server = "Microsoft-IIS/8.0"; "X-AspNet-Version" = "4.0.30319"; "X-Powered-By" = "ASP.NET"; } }}

提前谢谢你!

【问题讨论】:

  • 您是否尝试将 ParameterEncoding 设置为AFJSONParameterEncoding?我不确定这是否会对您有所帮助。我的一个应用程序下载 PDF,但我最终使用 NSURLConnection,而不是 AFNetworking 来下载 PDF。我发现它工作得更好。如果您愿意,我可以与您分享该代码。
  • @RyanG 是的,我得到了ExtendedException","message":"This file is invalid."
  • 我刚刚更新了我上面的评论
  • @RyanG 是的,我会喜欢的。谢谢!

标签: ios objective-c afnetworking nsurlrequest


【解决方案1】:

我在没有 AFNetworking 的情况下在我的应用程序中下载 PDF/图像/WordDocs,我也遇到了问题,所以我决定只使用旧的 NSURLConnection。我的 NSURLRequest 不使用 POST 数据,但我在这里修改了 NSURLRequest 以获取 POST 数据。

文件下载完成后,我会提供一个 QLPreviewController 来显示它。 (这可以处理显示 PDF、图像或 word 文档。如果你也想看到它,它需要更多的代码)

在您的 .h 中声明 4 个属性:

@property (strong, nonatomic) NSNumber *reportLength;
@property (strong, nonatomic) NSURLConnection *reportConnection;
@property (strong, nonatomic) NSMutableData *reportData;
@property (strong, nonatomic) NSString *reportURL;

还将NSURLConnectionDelegate 添加到您的代表列表中

然后在.m中:

- (void)downloadReport:(NSString *)reqUID
{
    NSString *file = [NSString stringWithFormat:@"%@GetReport.ashx?requestUID=%@&deviceUID=%@&token=%@", _globals.baseURL, reqUID, [MySingleton getDeviceID], _globals.token];
    NSURL *fileURL = [NSURL URLWithString:file];

    NSMutableURLRequest *req = [NSURLRequest requestWithURL:fileURL];
    [req setHTTPMethod:@"POST"];
    NSString *postString = @"FileID=10772&requireUnCompression=1";
    [req setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];

    _reportConnection = [NSURLConnection connectionWithRequest:req delegate:self];
    _reportData = [NSMutableData data];
    [_reportConnection start];

}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [_reportData setLength:0];
    NSLog(@"didReceiveResponse %@: %@", [response URL], [(NSHTTPURLResponse*)response allHeaderFields]);
    _reportLength = [NSNumber numberWithLongLong:[response expectedContentLength]];

    if(_reportLength.longLongValue == 0)
    {
        [_reportConnection cancel];

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Empty Report" message:@"The report you requested is empty. " delegate:self cancelButtonTitle:@"Ok" otherButtonTitles: nil, nil];
        [alert show];
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    NSNumber *resourceLength = [NSNumber numberWithUnsignedInteger:[_reportData length]];
    [_reportData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSString *msg = [NSString stringWithFormat:@"Error"];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"There was an issue downloading the attachment. Please try again." message:msg delegate:self cancelButtonTitle:@"Not Now" otherButtonTitles: @"Yes", nil];
    [alert show];
}

//when finished save in documents directory
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSArray *dirArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,    NSUserDomainMask, YES);
    _reportURL = [NSString stringWithFormat:@"%@/%@", [dirArray objectAtIndex:0], [NSString stringWithFormat:@"%@.pdf", _currentRequestUID]];

    NSError *err;
    if ([_reportData writeToFile:_reportURL options:NSAtomicWrite error:&err] == NO) {
        NSLog(@"writeToFile error: %@", _reportURL);

        NSString *msg = [NSString stringWithFormat:@"There was an issue saving the attachment. Please try again."];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:msg delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
        [alert show];
    }
    else //pdf downloaded, display using QLPreviewController
    {        
        NSLog(@"Written: _reportURL: %@", _reportURL);
        QLPreviewController *previewController=[[QLPreviewController alloc]init];
        previewController.delegate=self;
        previewController.dataSource=self;
        UIBarButtonItem *btn = [[UIBarButtonItem alloc] initWithTitle:@"Close" style:UIBarButtonItemStylePlain target:self action:@selector(btnCloseQLTouch:)];
        [previewController.navigationItem setLeftBarButtonItems:[NSArray arrayWithObjects:btn, nil]];
        [self presentViewController:previewController animated:YES completion:nil];
    }
}

编辑

要让 QLPreviewController 正常工作,首先将 &lt;QuickLook.framework&gt; 添加到您的项目中,然后在您的 .h 中添加这些删除:

QLPreviewControllerDataSource, QLPreviewControllerDelegate

以下是显示文件所需的数据源/委托方法:

//quicklook datasource/ delegate

- (NSInteger) numberOfPreviewItemsInPreviewController: (QLPreviewController *) controller
{
    return 1;
}

- (id <QLPreviewItem>)previewController: (QLPreviewController *)controller previewItemAtIndex:(NSInteger)index
{
    return [NSURL fileURLWithPath:_reportURL];
}

【讨论】:

  • 感谢您的代码。我似乎仍然有问题。在“didReceiveResponse”中,它只给出了 327 的内容长度。对于应该是 210714 的图像。
  • 你能告诉我一旦你有了reportURL你是如何设置QLPreviewDatasource的吗?
  • 我添加了显示文件所需的其他 2 个函数。还在标题中添加了代表
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-04-14
  • 1970-01-01
  • 2014-11-25
  • 2014-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多