Skip to content

Instantly share code, notes, and snippets.

@dinowang
Last active December 29, 2020 16:16
Show Gist options
  • Save dinowang/9cb375ec7c0c6d8d0454e4ba1c4258e9 to your computer and use it in GitHub Desktop.
Save dinowang/9cb375ec7c0c6d8d0454e4ba1c4258e9 to your computer and use it in GitHub Desktop.
Objective-C program upload file to Azure Blob Storage with progress indicator
#import <AZSClient/AZSClient.h>
NSString *const AZURE_STORAGE_CONNECTION_STRING = @"DefaultEndpointsProtocol=https;AccountName=(your account name);AccountKey=(your account key);EndpointSuffix=core.windows.net";
NSString *const AZURE_STORAGE_CONTAINER = @"files";
NSString *const LOCAL_FILE_FILEPATH = @"/Users/dino/A.mp4";
NSString *const LOCAL_FILE_FILENAME = @"A.mp4";
NSError *error;
AZSCloudStorageAccount *account = [AZSCloudStorageAccount accountFromConnectionString:AZURE_STORAGE_CONNECTION_STRING error:&error];
AZSCloudBlobClient *client = [account getBlobClient];
AZSCloudBlobContainer *container = [client containerReferenceFromName:AZURE_STORAGE_CONTAINER];
[container createContainerIfNotExistsWithCompletionHandler:^(NSError *error, BOOL exists) {
@autoreleasepool {
AZSCloudBlockBlob *blob = [container blockBlobReferenceFromName:LOCAL_FILE_FILENAME];
NSUInteger size = [[[NSFileManager defaultManager] attributesOfItemAtPath:LOCAL_FILE_FILEPATH error:&error] fileSize];
NSInputStream *stream = [NSInputStream inputStreamWithFileAtPath:LOCAL_FILE_FILEPATH];
AZSOperationContext *operationContext = [[AZSOperationContext alloc] init];
operationContext.sendingRequest = ^(NSMutableURLRequest *request, AZSOperationContext *context) {
NSNumber *number = [stream propertyForKey:NSStreamFileCurrentOffsetKey];
if (number != nil) {
NSUInteger pos = [number longValue];
float percentage = ((float)pos / size) * 100;
NSLog(@"current %ld of %ld, %f%% completed", pos, size, percentage);
}
};
NSLog(@"upload started.");
[blob uploadFromStream:stream accessCondition:nil requestOptions:nil operationContext:operationContext completionHandler:^(NSError *error) {
NSLog(@"upload done.");
exit(0);
}];
}
}];
@jthake
Copy link

jthake commented Jun 19, 2018

Does this approach handle loss in Internet connection or App switching in iOS?

@dinowang
Copy link
Author

dinowang commented Jun 20, 2018

Hi @jthake
This approach doesn't change AZSClient's behavior. Just used for watching upload progress by stream current offset.

@vanessanajem
Copy link

The NSNumber number is returning nil. What could cause such a problem? I just started using this code and I have no time to search for the problem so if anyone has faced such an issue or could help please do.

@vanessanajem
Copy link

Does this approach handle loss in Internet connection or App switching in iOS?

Did you have a problem with the streamfilecurrentoffset variable? It is returning nil for me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment