수색…


AWS SDK를 사용하여 S3에 이미지 또는 비디오 업로드

예제를 시작하기 전에 위임 클래스 멤버가있는 Singleton을 작성하여 백그라운드에서 파일을 업로드하는 유스 케이스를 구현하고 앱이 계속 업로드되는 동안 파일을 업로드하는 동안 사용자가 앱을 계속 사용할 수 있도록하는 것이 좋습니다. 배경입니다.

우선 S3 구성을 나타내는 열거 형을 작성해야합니다.

enum S3Configuration : String
{
    case IDENTITY_POOL_ID   = "YourIdentityPoolId"
    case BUCKET_NAME        = "YourBucketName"
    case CALLBACK_KEY       = "YourCustomStringForCallBackWhenUploadingInTheBackground"
    case CONTENT_TYPE_IMAGE = "image/png"
    case CONTENT_TYPE_VIDEO = "video/mp4"
}

이제는 앱을 처음 시작할 때 자격 증명을 설정해야하므로 didFinishLaunchingWithOptions 메소드에서 AppDelegate 내부에 설정해야합니다 ( regionType 매개 변수에서 지역을 설정해야합니다).

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
{
  let credentialProvider = AWSCognitoCredentialsProvider(regionType: .EUWest1, identityPoolId: S3Configuration.IDENTITY_POOL_ID.rawValue)
  let configuration = AWSServiceConfiguration(region: .EUWest1, credentialsProvider: credentialProvider)
  AWSS3TransferUtility.registerS3TransferUtilityWithConfiguration(configuration, forKey: S3Configuration.CALLBACK_KEY.rawValue)
}

AppDelegate에 이미 있으므로 AWS SDK에서 처리하는 백그라운드 콜백을 구현해야합니다.

func application(application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: () -> Void)
{
    //  Will print the identifer you have set at the enum: .CALLBACK_KEY
    print("Identifier: " + identifier)
    //  Stores the completion handler.
    AWSS3TransferUtility.interceptApplication(application,
                                              handleEventsForBackgroundURLSession: identifier,
                                              completionHandler: completionHandler)
}

이제 사용자가 앱을 배경으로 이동하면 업로드가 실제 업로드를 계속합니다.

AWS SDK를 사용하여 파일을 업로드하려면 파일을 장치에 쓰고 SDK에 실제 경로를 제공해야합니다. 예를 들어 UIImage (비디오 일 수도 있음)를 상상해보십시오. 임시 폴더에이 파일을 씁니다.

// Some image....
let image = UIImage()
let fileURL = NSURL(fileURLWithPath: NSTemporaryDirectory()).URLByAppendingPathComponent(fileName)
let filePath = fileURL.path!
let imageData = UIImageJPEGRepresentation(image, 1.0)
imageData!.writeToFile(filePath, atomically: true)

FileURL과 fileName은 실제 업로드에 나중에 사용됩니다.

AWS SDK에서 제공하는 두 가지 클로저를 정의해야합니다.

  1. AWSS3TransferUtilityUploadCompletionHandlerBlock - 업로드 완료 시점을 알려주는 클로저입니다.
  2. AWSS3TransferUtilityUploadProgressBlock - 전송 된 각 바이트를 통지하는 클로저

싱글 톤 (Singleton)을 가지려는 경우 클래스 멤버로 이러한 유형을 정의해야합니다. 구현은 다음과 같아야합니다.

var completionHandler : AWSS3TransferUtilityUploadCompletionHandlerBlock? =
    { (task, error) -> Void in

        if ((error) != nil)
        {
          print("Upload failed")
        }
        else
        {
          print("File uploaded successfully")
        }
    }

var progressBlock : AWSS3TransferUtilityUploadProgressBlock? = 
    { [unowned self] (task, bytesSent:Int64, totalBytesSent:Int64,  totalBytesExpectedToSend:Int64) -> Void in

     let progressInPercentage = Float(Double(totalBytesSent) / Double(totalBytesExpectedToSend)) * 100
     print(progressInPercentage)
    }

참고 : Singleton을 사용하는 경우 진행 상황을보고하거나 파일을 완료 할 때 다시보고 할 대리자를 정의 할 수 있습니다. 싱글 톤을 사용하지 않는다면 관련 유형을 가진 정적 메서드를 만들 수 있습니다 :

    static func uploadImageToS3(fileURL : NSURL,
                               fileName : String,
                progressFunctionUpdater : Float -> Void,
                            resultBlock : (NSError?) -> Void)
{
 //    Actual implementation .....
 //    ...
 //    ...
}
  1. progressFunctionUpdater - progressFunctionUpdater 이있는 함수로 다시보고합니다.
  2. resultBlock - nil을 반환하고 업로드가 성공적으로 resultBlock 오류 객체를 보냅니다.

신사 숙녀 여러분, 실제 업로드 :

        let fileData = NSData(contentsOfFile: fileURL.relativePath!)

        let expression = AWSS3TransferUtilityUploadExpression()
        expression.uploadProgress = progressBlock
        
        let transferUtility = AWSS3TransferUtility.S3TransferUtilityForKey(S3Configuration.CALLBACK_KEY.rawValue)
        
        transferUtility?.uploadData(fileData!,
            bucket: S3Configuration.BUCKET_NAME.rawValue,
            key: fileName,
            contentType: S3Configuration.CONTENT_TYPE_IMAGE.rawData,
            expression: expression,
            completionHander: completionHandler).continueWithBlock
            { (task : AWSTask) -> AnyObject? in
                
                if let error = task.error
                {
                    print(error)
                }
                if let exception = task.exception
                {
                    print("Exception: " + exception.description)
                }
                if let uploadTask = task.result as? AWSS3TransferUtilityUploadTask
                {
                    print("Upload started...")
                }
                
                return nil
        }

해피 S3 업로드 :)



Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow