2013-10-17 44 views
0

我基本上試圖下載一個文件,可以從PDF到PNG。我正在使用AFNetworking 1.x.AFNetworking - 下載文件,意外的消息格式'原始'

不過,我得到一個錯誤:

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"; } }}

預先感謝您!

+0

您是否嘗試過將ParameterEncoding設置爲'AFJSONParameterEncoding'?我不確定這是否會幫助你。我的一個應用程序下載PDF文件,但我最終使用NSURLConnection,而不是AFNetworking下載PDF文件。我發現它效果更好。如果您希望我可以與您分享該代碼。 – RyanG

+0

@RyanG是的,我得到了'ExtendedException「,」message「:」這個文件無效。「 – Alan

+0

我剛剛更新了我的評論 – RyanG

回答

1

我在沒有AFNetworking的情況下在我的應用程序中下載了PDF/Images/WordDocs,我也遇到了問題,所以我決定只使用舊的NSURLConnection。我的NSURLRequest不使用POST數據,但我在這裏修改了POST數據的NSURLRequest。

一旦文件完成下載,我提出了一個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工作首先添加<QuickLook.framework>到您的項目,然後在您的.h添加這些deletages:

QLPreviewControllerDataSource, QLPreviewControllerDelegate 

以下是顯示文件所需的數據源/委託方法:

//quicklook datasource/ delegate 

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

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

謝謝你的代碼。在「didReceiveResponse」中,它只給出了327的內容長度。對於應該是210714的圖像。 – Alan

+0

可以告訴我如何在設置了reportURL後設置QLPreviewDatasource ? – Alan

+1

我添加了其他2個你需要用來顯示文件的函數..也在代碼頭中添加代表 – RyanG