如何在Azure Swift中循环上传blob?

时间:2018-03-27 04:35:24

标签: swift azure azure-storage-blobs

我想上传到azure swift中的blob,但我不知道上传完成后转到segue这里是代码

//Save the image to the azurecloud
    do {
        let account = try AZSCloudStorageAccount(fromConnectionString:azureAccessKey) //I stored the property in my header file
        let blobClient: AZSCloudBlobClient = account.getBlobClient()
        let blobContainer: AZSCloudBlobContainer = blobClient.containerReference(fromName: containerName)

        let imageName =  "SampleList"

        let blob: AZSCloudBlockBlob = blobContainer.blockBlobReference(fromName: imageName)


        for (index, item) in uploadedImages.enumerated() {
            let productNameFixed = productNameTextField.text!.replacingOccurrences(of: " ", with: "_", options: .literal, range: nil)
            let imageSubName = String(userId) + "_" + productNameFixed
            let imageName =  imageSubName + "_" + String(index)

            let blob: AZSCloudBlockBlob = blobContainer.blockBlobReference(fromName: imageName)
            let imageData = UIImagePNGRepresentation(item)



            blob.upload(from: imageData!, completionHandler: {(NSError) -> Void in
                NSLog("Uploaded" + imageName)
                print("We have uploaded the image")

                self.checkBoxForMovingOn.append(index)

            })
        }





        print("done uploading")
        self.performSegue(withIdentifier: "productPostSuccessful", sender:  self)

我想基本知道我的图像列表何时完成上传,这样我就可以转到新的控制器来显示这些图像。发生的事情是我在没有完成图像上传的情况下转向控制器,我收到了错误。

1 个答案:

答案 0 :(得分:0)

您是否知道要上传的图片数量?

我不熟悉swift,但会为这种情况提供合理的答案,你可以使用两种情况:

我建议检查文件堆栈,它在swift上有一个使用Azure Blob上传的示例,并跟踪swift中的进度:

// Initialize a `Policy` with the expiry time and permissions you need.
let oneDayInSeconds: TimeInterval = 60 * 60 * 24 // expires tomorrow
let policy = Policy(// Set your expiry time (24 hours in our case)
                    expiry: Date(timeIntervalSinceNow: oneDayInSeconds),
                    // Set the permissions you want your policy to have
                    call: [.pick, .read, .store])

// Initialize a `Security` object by providing a `Policy` object and your app secret.
// You can find and/or enable your app secret in the Developer Portal.
guard let security = try? Security(policy: policy, appSecret: "YOUR-APP-SECRET") else {
    return
}

// Get an URL pointing to the local file you would like to upload.
guard let localURL = Bundle.main.url(forResource: "YOUR-IMAGE", withExtension: "jpg") else {
    return
}

// Initialize your `Client` object by passing a valid API key, and security options.
let client = Client(apiKey: "YOUR-API-KEY", security: security)

let uploadProgress: (Progress) -> Void = { progress in
    // Here you may update the UI to reflect the upload progress.
    print("Progress: \(progress)")
}

// Store options
let storeOptions: StorageOptions = StorageOptions(// Store location (e.g. S3, Dropbox, Rackspace, Azure, Google Cloud Storage)
                                                  location: .s3,
                                                  // AWS Region for S3 (e.g. "us-east-1", "eu-west-1", "ap-northeast-1", etc.)
                                                  region: "us-east-1",
                                                  // The name of your S3 bucket
                                                  container: "YOUR-S3-BUCKET",
                                                  // Destination path in the store.
                                                  // You may use a path to a folder (e.g. /public/) or,
                                                  // alternatively a path containing a filename (e.g. /public/oncorhynchus.jpg).
                                                  // When using a path to a folder, the uploaded file will be stored at that folder using a
                                                  // filename derived from the original filename.
                                                  // When using a path to a filename, the uploaded file will be stored at the given path
                                                  // using the filename indicated in the path.
                                                  path: "/public/oncorhynchus.jpg",
                                                  // Access permissions (either public or private)
                                                  access: .public)

// Call the function in your `Client` instance that takes care of file uploading.
// Please notice that some of the parameters are optional and have default values.
let multiPartUpload = client.multiPartUpload(// Set the URL pointing to the local file you want to upload.
                                             from: localURL,
                                             // Set the destination storage location here.
                                             // If none given, S3 location with default options is assumed.
                                             storeOptions: storeOptions,
                                             // Set to `false` if you don't want to use
                                             // Intelligent Ingestion regardless of whether it is available
                                             // for you.
                                             useIntelligentIngestionIfAvailable: true,
                                             // Set the dispatch queue where you want your upload progress
                                             // and completion handlers to be called.
                                             // Remember that any UI updates should be performed on the
                                             // main queue.
                                             // You can omit this parameter, and the main queue will be
                                             // used by default.
                                             queue: .main,
                                             // Set your upload progress handler here (optional)
                                             uploadProgress: uploadProgress) { response in
    // Try to obtain Filestack handle
    if let json = response?.json, let handle = json["handle"] as? String {
        // Use Filestack handle
    } else if let error = response?.error {
        // Handle error
    }
}

// Cancelling ongoing multipart upload.
multipartUpload.cancel()

来源: https://github.com/filestack/filestack-swift