ダウンロード

Background Transfer を使って Object Body をダウンロードする例を挙げます。

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");
    }

ここでは以下の処理を実施しています。

  • KiiObject インスタンスを作成。
  • generateDownloadRequest() メソッドを実行して、NSURLRequest インスタンスを作成。
  • バックグラウンド実行が可能な NSURLSession インスタンスを作成。
  • NSURLRequest インスタンスを指定して downloadTaskWithRequest(_:) メソッドを実行し、NSURLSessionDownloadTask インスタンスを作成。
  • resume() メソッドを実行して、ファイルのダウンロードを開始。

ダウンロードしたファイルは一時領域に保存され、そのパスは NSURLSessionDownloadDelegateurlSession(_:downloadTask:didFinishDownloadingToURL:) から通知されます。必要に応じてダウンロードしたファイルを移動するなどの処理を行ってください。

処理結果については NSURLSessionDownloadDelegateurlSession(_:task:didCompleteWithError:) で通知されます。