iosobjective-ciphonedownloadkinvey

Downloading Files from Kinvey in iOS


I have read documents over kinvey here: http://devcenter.kinvey.com/ios/guides/files#DownloadingtoCachesDirectory

They have provided sample function as well:

[KCSFileStore downloadData:@"myId" completionBlock:^(NSArray *downloadedResources, NSError *error) {
if (error == nil) {
    KCSFile* file = downloadedResources[0];
    NSData* fileData = file.data;
    id outputObject = nil;
    if ([file.mimeType hasPrefix:@"text"]) {
        outputObject = [[NSString alloc] initWithData:fileData encoding:NSUTF8StringEncoding];
    } else if ([file.mimeType hasPrefix:@"image"]) {
        outputObject = [UIImage imageWithData:fileData];
    }
    NSLog(@"downloaded: %@", outputObject);
} else {
    NSLog(@"Got an error: %@", error);
 }
} progressBlock:nil]; 

But when i replaced "myId" with file id it gave me this error:

Error Domain=KCSServerErrorDomain Code=401 "The credentials used to authenticate this request are not authorized to run this operation. Please retry your request with appropriate credentials"

While i can access other collections i have created over kinvey (same user) with same credentials (secret,api_key)

Is there any other requirement before calling this function?

Thanks


Solution

  • I had the same problem. I reached out and got help from the kinvey support team.

    I solved the problem by setting the "acl" for each file that I upload. According to the iOS Files guide under upload options: "By default the file will only be available to the creating user.", this was what was causing the problem for me.

    I upload files like this now:

        let metadata = KCSMetadata()
        metadata.setGloballyReadable(true)
    
        let data = UIImagePNGRepresentation(image)
    
        KCSFileStore.uploadData(
            data,
            options: options: [KCSFileACL : metadata],
            completionBlock: {KCSFileUploadCompletionBlock!},
            progressBlock: nil)
    

    This allows anyuser to read that specific file. I Use a KCSUser.createAutogeneratedUser() to read the files afterwards.

    Yes, you will have access to other collections under the same kinvey app, but the permissions needs to be set for the files collection. So the file you describe as "myId" needs to have the proper permissions set, before it can be downloaded by another user than the user that upload the file.