アップロード

Background Transfer を使って Object Body をアップロードする例を挙げます。

Swift 3:

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

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

  • (必要に応じて)KiiObject にキーと値のペアをセットし、save(_:) メソッドを実行してオブジェクトを保存。ファイル名、ファイルサイズ、Object Body の有無などを登録しておくことも可能。
  • generateUploadRequest(_:) メソッドを実行して、NSURLRequest インスタンスを作成。
  • バックグラウンド実行が可能な NSURLSession インスタンスを作成。
  • アップロード対象ファイル(sample.mp4)のリファレンスを作成。
  • NSURLRequest インスタンスとアップロード対象ファイルのリファレンスを指定して uploadTaskWithRequest(_:fromFile:) メソッドを実行し、NSURLSessionUploadTask インスタンスを作成。
  • resume() メソッドを実行して、ファイルのアップロードを開始。

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