Using iOS Dropbox SDK to do a Chunked Upload of Core Data

前端 未结 1 1817
青春惊慌失措
青春惊慌失措 2021-02-04 17:39

I have an iOS app that uses Core Data for persistent data storage. I integrated Dropbox as a way for users to perform a a backup of the persistent store file (appname.sqlite).<

1条回答
  •  借酒劲吻你
    2021-02-04 18:13

    I'm going to answer this myself just in case anyone else has the same issue.

    It turns out that I was making this way more difficult than it needed to be. The Dropbox SDK handles chunking the files so I just needed to initate the transfer and react to the delegate calls. The methods used are:

    To send a file chunk - for the first chunk, use nil for the uploadId and 0 for the offset:

    - (void)uploadFileChunk:(NSString *)uploadId offset:(unsigned long long)offset fromPath:(NSString *)localPath;
    

    After sending the last chunk, use this method to commit the upload:

    - (void)uploadFile:(NSString *)filename toPath:(NSString *)parentFolder withParentRev:(NSString *)parentRev fromUploadId:(NSString *)uploadId;
    

    I handled the delegate method as follows:

        - (void)restClient:(DBRestClient *)client uploadedFileChunk:(NSString *)uploadId newOffset:(unsigned long long)offset fromFile:(NSString *)localPath expires:(NSDate *)expiresDate
        {
            unsigned long long fileSize = [[[NSFileManager defaultManager]attributesOfItemAtPath:[FileHelper localDatabaseFilePath] error:nil]fileSize];
    
            if (offset >= fileSize)
            {
                //Upload complete, commit the file.
                [self.restClient uploadFile:DATABASE_FILENAME toPath:[FileHelper remoteDatabaseDirectory] withParentRev:self.databaseRemoteRevision fromUploadId:uploadId];
            }
            else
            {
                //Send the next chunk and update the progress HUD.
                self.progressHUD.progress = (float)((float)offset / (float)fileSize);
                [self.restClient uploadFileChunk:uploadId offset:offset fromPath:[FileHelper localDatabaseFilePath]];
            }
        }
    

    Since the main problem that I was trying to address was handling poor connections I implemented delegate method for failed chunk uploads:

    - (void)restClient:(DBRestClient *)client uploadFileChunkFailedWithError:(NSError *)error
    {
        if (error != nil && (self.uploadErrorCount < DROPBOX_MAX_UPLOAD_FAILURES))
        {
            self.uploadErrorCount++;
            NSString* uploadId = [error.userInfo objectForKey:@"upload_id"];
            unsigned long long offset = [[error.userInfo objectForKey:@"offset"]unsignedLongLongValue];
            [self.restClient uploadFileChunk:uploadId offset:offset fromPath:[FileHelper localDatabaseFilePath]];
        }
        else
        {
          //show an error message and cancel the process
        }
    }
    

    0 讨论(0)
提交回复
热议问题