如何使用Swift将图像上传到Azure

时间:2015-06-02 04:41:29

标签: ios swift azure azure-mobile-services

我正在开发一个需要使用Swift在Azure中存储图像的应用程序。

有没有任何有用的例子?如果没有,你可以给我一个建议吗?

3 个答案:

答案 0 :(得分:5)

这是一个简单的例子。

1-从这里开始:https://azure.microsoft.com/en-us/documentation/articles/storage-ios-how-to-use-blob-storage/

2-获取SDK

3-这是代码:

let account = AZSCloudStorageAccount(fromConnectionString:AZURE_STORAGE_CONNECTION_STRING) //I stored the property in my header file
let blobClient: AZSCloudBlobClient = account.getBlobClient()
let blobContainer: AZSCloudBlobContainer = blobClient.containerReferenceFromName("<yourContainerName>")
blobContainer.createContainerIfNotExistsWithAccessType(AZSContainerPublicAccessType.Container, requestOptions: nil, operationContext: nil) { (NSError, Bool) -> Void in
   if ((NSError) != nil){
      NSLog("Error in creating container.")
   }
   else {
      let blob: AZSCloudBlockBlob = blobContainer.blockBlobReferenceFromName(<nameOfYourImage> as String) //If you want a random name, I used let imageName = CFUUIDCreateString(nil, CFUUIDCreate(nil))          
      let imageData = UIImagePNGRepresentation(<yourImageData>)

      blob.uploadFromData(imageData!, completionHandler: {(NSError) -> Void in
      NSLog("Ok, uploaded !")
      })
    }
}

享受:)

答案 1 :(得分:2)

您必须使用他们的REST API,但他们现在正在使用SDK

有几个在iOS上使用REST API的例子。粗略搜索出现:Uploading to azure blob storage from SAS URL returns 404 status

在Github上也有这个例子 - https://github.com/Ajayi13/BlobExample-Swift

答案 2 :(得分:0)

在iOS 11和Swift 4中,你可以这样做:

private let containerName = "<Your Name>"
private let connectionString = "<Your String>"

do {
    let account = try AZSCloudStorageAccount(fromConnectionString: connectionString)
    let blobClient = account?.getBlobClient()
    let blobContainer = blobClient?.containerReference(fromName: containerName)

    let currentDate = Date()
    let fileName = String(currentDate.timeIntervalSinceReferenceDate)+".jpg"
    let blob = blobContainer?.blockBlobReference(fromName: now)
    blob?.upload(from: imageData, completionHandler: {(error)->Void in
        print(now, "uploaded!") // imageData is the data you want to upload
    })
} catch {
    print(error)
}

这只是一个例子。希望它有所帮助。