Uploading an Object Body
The following sample code shows how to upload an object body with the Background Transfer service.
Swift:
class delegate : NSObject , URLSessionDataDelegate {
func uploadObjectBody (){
// Check if a KiiUser is logged in.
if KiiUser . current () == nil {
return
}
// Create a KiiObject in a user-scope bucket.
let bucket = KiiUser . current () !. bucket ( withName : "MyBucket" )
let object = bucket . createObject ()
// Set key-value pairs.
object . setObject ( "myVideo" , forKey : "title" )
object . setObject ( NSNumber ( value : 10485760 as Int ), forKey : "fileSize" )
do {
// Save the KiiObject.
try object . saveSynchronous ()
} catch let error as NSError {
// Handle the error.
return
}
// Prepare a URLSession object to upload the object body in the background.
let contentType = "video/mp4"
let uploadRequest = object . generateUploadRequest ( contentType ) !
let uuidStr = UUID () . uuidString
let randomSessionIdentifier = uuidStr . lowercased ()
let sessionConfig : URLSessionConfiguration
sessionConfig = URLSessionConfiguration . background ( withIdentifier : randomSessionIdentifier )
sessionConfig . allowsCellularAccess = true
let session = URLSession ( configuration : sessionConfig , delegate : self , delegateQueue : OperationQueue . main )
// Specify a file to upload.
let targetDirectory : NSString = ( NSHomeDirectory () as NSString ) . appendingPathComponent ( "Documents" ) as NSString
let sourceFilePath = targetDirectory . appendingPathComponent ( "sample.mp4" )
let sourceFileURL = URL ( fileURLWithPath : sourceFilePath )
// Create an upload task.
let uploadTask = session . uploadTask ( with : uploadRequest , fromFile : sourceFileURL )
// Start or resume the task.
uploadTask . resume ()
}
@objc fileprivate func urlSession ( _ session : URLSession , task : URLSessionTask , didSendBodyData bytesSent : Int64 , totalBytesSent : Int64 , totalBytesExpectedToSend : Int64 ) {
// The upload is in progress.
print ( "Progress : \( Float ( totalBytesSent / totalBytesExpectedToSend ) ) " )
}
@objc fileprivate func urlSession ( _ session : URLSession , task : URLSessionTask , didCompleteWithError error : Error ? ){
if error != nil {
// Handle the error.
print ( "Background transfer is failed" )
return
}
// Check the HTTP status code.
let response = task . response as! HTTPURLResponse
if response . statusCode >= 300 {
print ( "Background transfer is failed, status code: \( response . statusCode ) " )
return
}
print ( "Background transfer succeeded" )
}
}
class delegate : NSObject , URLSessionDataDelegate {
func uploadObjectBody (){
// Check if a KiiUser is logged in.
if KiiUser . current () == nil {
return
}
// Create a KiiObject in a user-scope bucket.
let bucket = KiiUser . current () !. bucket ( withName : "MyBucket" )
let object = bucket . createObject ()
// Set key-value pairs.
object . setObject ( "myVideo" , forKey : "title" )
object . setObject ( NSNumber ( value : 10485760 as Int ), forKey : "fileSize" )
// Save the KiiObject.
object . save { ( object : KiiObject ?, error : Error ?) -> Void in
if error != nil {
print ( "Object creation error!" )
return
}
// Prepare a URLSession object to upload the object body in the background.
let contentType = "video/mp4"
let uploadRequest = object !. generateUploadRequest ( contentType ) !
let uuidStr = UUID () . uuidString
let randomSessionIdentifier = uuidStr . lowercased ()
let sessionConfig : URLSessionConfiguration
sessionConfig = URLSessionConfiguration . background ( withIdentifier : randomSessionIdentifier )
sessionConfig . allowsCellularAccess = true
let session = URLSession ( configuration : sessionConfig , delegate : self , delegateQueue : OperationQueue . main )
// Specify a file to upload.
let targetDirectory : NSString = ( NSHomeDirectory () as NSString ) . appendingPathComponent ( "Documents" ) as NSString
let sourceFilePath = targetDirectory . appendingPathComponent ( "sample.mp4" )
let sourceFileURL = URL ( fileURLWithPath : sourceFilePath )
// Create an upload task.
let uploadTask = session . uploadTask ( with : uploadRequest , fromFile : sourceFileURL )
// Start or resume the task.
uploadTask . resume ()
}
}
@objc fileprivate func urlSession ( _ session : URLSession , task : URLSessionTask , didSendBodyData bytesSent : Int64 , totalBytesSent : Int64 , totalBytesExpectedToSend : Int64 ) {
// The upload is in progress.
print ( "Progress : \( Float ( totalBytesSent / totalBytesExpectedToSend ) ) " )
}
@objc fileprivate func urlSession ( _ session : URLSession , task : URLSessionTask , didCompleteWithError error : Error ? ){
if error != nil {
// Handle the error.
print ( "Background transfer is failed" )
return
}
// Check the HTTP status code.
let response = task . response as! HTTPURLResponse
if response . statusCode >= 300 {
print ( "Background transfer is failed, status code: \( response . statusCode ) " )
return
}
print ( "Background transfer succeeded" )
}
}
Objective-C:
- ( void ) uploadObjectBody {
// Check if a KiiUser is logged in.
if ([ KiiUser currentUser ] == nil ) {
return ;
}
// Create a KiiObject in a user-scope bucket.
KiiBucket * bucket = [[ KiiUser currentUser ] bucketWithName : @"MyBucket" ];
KiiObject * object = [ bucket createObject ];
// Set key-value pairs.
[ object setObject : @"MyVideo"
forKey : @"title" ];
[ object setObject :[ NSNumber numberWithInt : 10485760 ]
forKey : @"fileSize" ];
// Save the KiiObject.
NSError * error = nil ;
[ object saveSynchronous : & error ];
if ( error != nil ) {
// Handle the error.
NSLog ( @"Object creation error!" );
return ;
}
// Prepare an NSURLSession object to upload the object body in the background.
NSString * contentType = @"video/mp4" ;
NSURLRequest * uploadRequest = [ object generateUploadRequest : contentType ];
CFUUIDRef uuid = CFUUIDCreate ( kCFAllocatorDefault );
NSString * uuidStr = ( __bridge_transfer NSString * ) CFUUIDCreateString ( kCFAllocatorDefault , uuid );
CFRelease ( uuid );
NSString * randomSessionIdentifier = [ uuidStr lowercaseString ];
NSURLSessionConfiguration * sessionConfig ;
sessionConfig = [ NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier : randomSessionIdentifier ];
sessionConfig . allowsCellularAccess = YES ;
NSURLSession * session = [ NSURLSession sessionWithConfiguration : sessionConfig
delegate : self
delegateQueue : [ NSOperationQueue mainQueue ]];
// Specify a file to upload.
NSString * targetDirectory = [ NSHomeDirectory () stringByAppendingPathComponent : @"Documents" ];
NSString * sourceFilePath = [ targetDirectory stringByAppendingPathComponent : @"sample.mp4" ];
NSURL * sourceFileURL = [ NSURL fileURLWithPath : sourceFilePath ];
// Create an upload task.
NSURLSessionUploadTask * uploadTask = [ session uploadTaskWithRequest : uploadRequest
fromFile : sourceFileURL ];
// Start or resume the task.
[ uploadTask resume ];
}
- ( void ) URLSession : ( NSURLSession * ) session task : ( NSURLSessionTask * ) task didSendBodyData : ( int64_t ) bytesSent totalBytesSent : ( int64_t ) totalBytesSent totalBytesExpectedToSend : ( int64_t ) totalBytesExpectedToSend {
// The upload is in progress.
NSLog ( @"Progress : %f" , ( float ) totalBytesSent / totalBytesExpectedToSend );
}
- ( void ) URLSession : ( NSURLSession * ) session task : ( NSURLSessionTask * ) task didCompleteWithError : ( NSError * ) error {
if ( error != nil ) {
// Handle the error.
NSLog ( @"Background transfer is failed" );
return ;
}
// Check the HTTP status code.
NSHTTPURLResponse * response = ( NSHTTPURLResponse * ) task . response ;
if ([ response statusCode ] >= 300 ) {
NSLog ( @"Background transfer is failed, status code: %ld" , ( long )[ response statusCode ]);
return ;
}
NSLog ( @"Background transfer succeeded" );
}
- ( void ) uploadObjectBody {
// Check if a KiiUser is logged in.
if ([ KiiUser currentUser ] == nil ) {
return ;
}
// Create a KiiObject in a user-scope bucket.
KiiBucket * bucket = [[ KiiUser currentUser ] bucketWithName : @"MyBucket" ];
KiiObject * object = [ bucket createObject ];
// Set key-value pairs.
[ object setObject : @"MyVideo"
forKey : @"title" ];
[ object setObject :[ NSNumber numberWithInt : 10485760 ]
forKey : @"fileSize" ];
// Save the KiiObject.
[ object saveWithBlock : ^ ( KiiObject * object , NSError * error ) {
if ( error != nil ) {
// Handle the error.
NSLog ( @"Object creation error!" );
return ;
}
// Prepare an NSURLSession object to upload the object body in the background.
NSString * contentType = @"video/mp4" ;
NSURLRequest * uploadRequest = [ object generateUploadRequest : contentType ];
CFUUIDRef uuid = CFUUIDCreate ( kCFAllocatorDefault );
NSString * uuidStr = ( __bridge_transfer NSString * ) CFUUIDCreateString ( kCFAllocatorDefault , uuid );
CFRelease ( uuid );
NSString * randomSessionIdentifier = [ uuidStr lowercaseString ];
NSURLSessionConfiguration * sessionConfig ;
sessionConfig = [ NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier : randomSessionIdentifier ];
sessionConfig . allowsCellularAccess = YES ;
NSURLSession * session = [ NSURLSession sessionWithConfiguration : sessionConfig
delegate : self
delegateQueue: [ NSOperationQueue mainQueue ]];
// Specify a file to upload.
NSString * targetDirectory = [ NSHomeDirectory () stringByAppendingPathComponent : @"Documents" ];
NSString * sourceFilePath = [ targetDirectory stringByAppendingPathComponent : @"sample.mp4" ];
NSURL * sourceFileURL = [ NSURL fileURLWithPath : sourceFilePath ];
// Create an upload task.
NSURLSessionUploadTask * uploadTask = [ session uploadTaskWithRequest : uploadRequest
fromFile : sourceFileURL ];
// Start or resume the task.
[ uploadTask resume ];
}];
}
- ( void ) URLSession : ( NSURLSession * ) session task : ( NSURLSessionTask * ) task didSendBodyData : ( int64_t ) bytesSent totalBytesSent : ( int64_t ) totalBytesSent totalBytesExpectedToSend : ( int64_t ) totalBytesExpectedToSend {
// The upload is in progress.
NSLog ( @"Progress : %f" , ( float ) totalBytesSent / totalBytesExpectedToSend );
}
- ( void ) URLSession : ( NSURLSession * ) session task : ( NSURLSessionTask * ) task didCompleteWithError : ( NSError * ) error {
if ( error != nil ) {
// Handle the error.
NSLog ( @"Background transfer is failed" );
return ;
}
// Check the HTTP status code.
NSHTTPURLResponse * response = ( NSHTTPURLResponse * ) task . response ;
if ([ response statusCode ] >= 300 ) {
NSLog ( @"Background transfer is failed, status code: %ld" , ( long )[ response statusCode ]);
return ;
}
NSLog ( @"Background transfer succeeded" );
}
Here is what is happening in the sample code:
Sets key-value pairs (e.g., file name, file size, and the availability of an object body) in a KiiObject as needed and save them with the save(_:)
method.
Creates an NSURLRequest
instance with the generateUploadRequest(_:)
method.
Creates an NSURLSession
instance that can be run in the background.
Creates a reference to the target file (sample.mp4).
Creates an NSURLSessionUploadTask
instance by calling the uploadTask(_:fromFile:)
method with the NSURLRequest
instance and the file reference.
Starts uploading by calling the resume()
method.
The result will be notified by the urlSession(_:task:didCompleteWithError:)
method of the NSURLSessionDataDelegate
class.