Downloading an Object Body

The following sample code shows how to download an object body with the Background Transfer service.

Swift:

  • class delegate :NSObject, URLSessionDataDelegate,URLSessionDownloadDelegate{
    
      func downloadObjectBody(){
        // Check if a KiiUser is logged in.
        if KiiUser.current() == nil{
          return
        }
        // Instantiate the target KiiObject.
        let object = KiiObject(uri: "Set the URI of an existing KiiObject here")!
    
        // Prepare a URLSession object to download the object body in the background.
        let downloadRequest = object.generateDownloadRequest()!
        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)
    
        // Create a download task.
        let downloadTask = session.downloadTask(with: downloadRequest)
    
        // Start or resume the task.
        downloadTask.resume()
      }
    
      @objc fileprivate func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
        // The download is in progress.
        print("Progress : \(Float(totalBytesWritten / totalBytesExpectedToWrite))")
      }
    
      @objc fileprivate func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
        // Note: The file will be downloaded in a temporary area. Move the downloaded file to a persistent area if needed.
    
        // Specify the file destination.
        let targetDirectory : NSString = (NSHomeDirectory() as NSString).appendingPathComponent("Documents") as NSString
        let downloadFilePathStr = targetDirectory.appendingPathComponent("sample.mp4")
        let downloadFilePath = URL(fileURLWithPath: downloadFilePathStr)
        let fileManager = FileManager.default
    
        do{
          try fileManager.moveItem(at: location, to: downloadFilePath)
        }catch (let error){
          print("File move is failed \(error)")
          return
        }
        print("Download succeeded")
      }
    
      @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, URLSessionDownloadDelegate{
    
      func downloadObjectBody(){
        // Check if a KiiUser is logged in.
        if KiiUser.current() == nil{
          return
        }
        // Instantiate the target KiiObject.
        let object = KiiObject(uri: "Set the URI of an existing KiiObject here")!
    
        // Prepare a URLSession object to download the object body in the background.
        let downloadRequest = object!.generateDownloadRequest()!
        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)
    
        // Create a download task.
        let downloadTask = session.downloadTask(with: downloadRequest)
    
        // Start or resume the task.
        downloadTask.resume()
      }
    
      @objc fileprivate func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
        // The download is in progress.
        print("Progress : \(Float(totalBytesWritten / totalBytesExpectedToWrite))")
      }
    
      @objc fileprivate func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
        // Note: The file will be downloaded in a temporary area. Move the downloaded file to a persistent area if needed.
    
        // Specify the file destination.
        let targetDirectory : NSString = (NSHomeDirectory() as NSString).appendingPathComponent("Documents") as NSString
        let downloadFilePathStr = targetDirectory.appendingPathComponent("sample.mp4")
        let downloadFilePath = URL(fileURLWithPath: downloadFilePathStr)
        let fileManager = FileManager.default
    
        do{
          try fileManager.moveItem(at: location, to: downloadFilePath)
        }catch (let error){
          print("File move is failed \(error)")
          return
        }
        print("Download succeeded")
      }
    
      @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)downloadObjectBody {
      // Check if a KiiUser is logged in.
      if ([KiiUser currentUser] == nil) {
        return;
      }
      // Instantiate the target KiiObject.
      KiiObject *object = [KiiObject objectWithURI:@"Set the URI of an existing KiiObject here"];
    
      // Prepare an NSURLSession object to download the object body in the background.
      NSURLRequest *downloadRequest = [object generateDownloadRequest];
      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]];
    
      // Create a download task.
      NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:downloadRequest];
    
      // Start or resume the task.
      [downloadTask resume];
    }
    
    - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
      // The download is in progress.
      NSLog(@"Progress : %f", (float) totalBytesWritten / totalBytesExpectedToWrite);
    }
    
    - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
      // Note: The file will be downloaded in a temporary area. Move the downloaded file to a persistent area if needed.
    
      // Specify the file destination.
      NSString *targetDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
      NSString *downloadFilePathStr = [targetDirectory stringByAppendingPathComponent:@"sample.mp4"];
      NSURL *downloadFilePath = [NSURL fileURLWithPath:downloadFilePathStr];
      NSFileManager *fileManager = [NSFileManager defaultManager];
      NSError *moveError = nil;
      [fileManager moveItemAtURL:location toURL:downloadFilePath error:&moveError];
    
      if (moveError != nil) {
        // Handle the error.
        NSLog(@"File move is failed");
        return;
      }
    }
    
    - (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)downloadObjectBody {
      // Check if a KiiUser is logged in.
      if ([KiiUser currentUser] == nil) {
        return;
      }
      // Instantiate the target KiiObject.
      KiiObject *object = [KiiObject objectWithURI:@"Set the URI of an existing KiiObject here"];
    
      // Prepare an NSURLSession object to download the object body in the background.
      NSURLRequest *downloadRequest = [object generateDownloadRequest];
      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]];
    
      // Create a download task.
      NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:downloadRequest];
    
      // Start or resume the task.
      [downloadTask resume];
    }
    
    - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
      // The download is in progress.
      NSLog(@"Progress : %f", (float) totalBytesWritten / totalBytesExpectedToWrite);
    }
    
    - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
      // Note: The file will be downloaded in a temporary area. Move the downloaded file to a persistent area if needed.
    
      // Specify the file destination.
      NSString *targetDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
      NSString *downloadFilePathStr = [targetDirectory stringByAppendingPathComponent:@"sample.mp4"];
      NSURL *downloadFilePath = [NSURL fileURLWithPath:downloadFilePathStr];
      NSFileManager *fileManager = [NSFileManager defaultManager];
      NSError *moveError = nil;
      [fileManager moveItemAtURL:location toURL:downloadFilePath error:&moveError];
    
      if (moveError != nil) {
        // Handle the error.
        NSLog(@"File move is failed");
        return;
      }
    }
    
    - (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:

  • Creates a KiiObject instance.
  • Creates an NSURLRequest instance by calling the generateDownloadRequest() method.
  • Creates an NSURLSession instance that can be run in the background.
  • Creates an NSURLSessionDownloadTask instance by calling the downloadTaskWithRequest(_:) method with the NSURLRequest instance.
  • Starts downloading by calling the resume() method.

The downloaded file will be stored in a temporary space, and its path will be notified by the urlSession(_:downloadTask:didFinishDownloadingToURL:) method of the NSURLSessionDownloadDelegate class. Move the file to the desired place as needed.

The result will be notified by the urlSession(_:task:didCompleteWithError:) method of the NSURLSessionDownloadDelegate class.