Search code examples
iosobjective-csdkafnetworkingxlsx

Reading .xlsx file iOS Objective C


I am trying to download .xlsx file from server using AFNetworking. But it gives me error saying:

Error Domain=com.alamofire.error.serialization.response Code=-1016 "Request failed: unacceptable content-type: application/zip" UserInfo={NSLocalizedDescription=Request failed: unacceptable content-type: application/zip

It shows whole response inside the NSError.

I don't want to use any third party library as I am integrating this in my SDK itself.


Solution

  • To Download .xlsx file in AFNetworking2.x. You can't use this code. This code is for Json Serialization. Reason:

    /* 
    In AFURLResponseSerialization.m this line will convert downloaded data to json, which make invalid serialization error 
    */
        responseObject = [NSJSONSerialization JSONObjectWithData:data options:self.readingOptions error:&serializationError];
    

    NOT Working Code :

        // This code will not work for XLSX File
            AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
            manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", nil];
    
            [manager GET:@"Link to xlsx File" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
                NSLog(@"JSON: %@", responseObject);
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                NSLog(@"Error: %@", error);
            }];
    

    Use this :

    https://github.com/AFNetworking/AFNetworking/tree/2.x#creating-a-download-task

     NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
        AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    
        NSURL *URL = [NSURL URLWithString:@"Link to xlsx File"];
        NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    
        NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
            NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
            return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
        } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
            NSLog(@"File downloaded to: %@", filePath);
        }];
        [downloadTask resume];