Subin K Kuriakose
Subin K Kuriakose

Reputation: 849

How to upload images to Azure using Swift

I am developing an app which needs to store images in Azure using Swift.

Is there any example that will be helpful ? If not can you give me a suggestion ?

Upvotes: 6

Views: 6128

Answers (4)

Shakeel Ahmed
Shakeel Ahmed

Reputation: 6021

Swift 5+ Easy Solution 100% Working

//usage of below mentioned extension 
    let currentDate1 = Date()
    let fileName = String(currentDate1.timeIntervalSinceReferenceDate)+".jpg"
    uploadImageToBlobStorage(token: "your sasToken", image: UIImage(named: "dummyFood")!, blobName: fileName)



//Blob Upload Storage
extension RegisterationViewController {

    func uploadImageToBlobStorage(token: String, image: UIImage, blobName: String) {
            
        let tempToken = token.components(separatedBy: "?")
    
        let sasToken = tempToken.last ?? ""
        let containerURL = "\(tempToken.first ?? "")"
        print("containerURL with SAS: \(containerURL) ")
    
        let azureBlobStorage = AzureBlobStorage(containerURL: containerURL, sasToken: sasToken)
        azureBlobStorage.uploadImage(image: image, blobName: blobName) { success, error in
            if success {
                print("Image uploaded successfully!")
                if let imageURL = self.getImageURL(storageAccountName: "yourContainerName", containerName: containerName, blobName: blobName, sasToken: "") {
                    print("Image URL: \(imageURL)")
                    self.userSignup(imageUrl: "\(imageURL)")
                } else {
                    print("Failed to construct image URL")
                }
            } else {
                print("Failed to upload image: \(error?.localizedDescription ?? "Unknown error")")
            }
        }
    return()
}

struct AzureBlobStorage {
    let containerURL: String
    let sasToken: String
    
    init(containerURL: String, sasToken: String) {
        self.containerURL = containerURL
        self.sasToken = sasToken
    }
    
   func uploadImage(image: UIImage, blobName: String, completion: @escaping (Bool, Error?) -> Void) {
        guard let imageData = image.jpegData(compressionQuality: 0.8) else {
            completion(false, NSError(domain: "", code: 0, userInfo: [NSLocalizedDescriptionKey: "Failed to convert image to data"]))
                return
            }
        
        let uploadURLString = "\(containerURL)/\(blobName)?\(sasToken)"
        guard let uploadURL = URL(string: uploadURLString) else {
            completion(false, NSError(domain: "", code: 0, userInfo: [NSLocalizedDescriptionKey: "Invalid URL"]))
                return
        }
        
        var request = URLRequest(url: uploadURL)
        request.httpMethod = "PUT"
        request.setValue("BlockBlob", forHTTPHeaderField: "x-ms-blob-type")
            request.setValue("image/jpeg", forHTTPHeaderField: "Content-Type")
            request.httpBody = imageData
        
            let session = URLSession.shared
            let task = session.dataTask(with: request) { data, response, error in
                if let error = error {
                    completion(false, error)
                    return
                }
            
                guard let httpResponse = response as? HTTPURLResponse else {
                    completion(false, NSError(domain: "", code: 0, userInfo: [NSLocalizedDescriptionKey: "Invalid response from server"]))
                return
                }
            
                if httpResponse.statusCode == 201 {
                    completion(true, nil)
                } else {
                    let statusCodeError = NSError(domain: "", code: httpResponse.statusCode, userInfo: [NSLocalizedDescriptionKey: "Failed to upload image, status code: \(httpResponse.statusCode)"])
                    completion(false, statusCodeError)
                }
            }
        
            task.resume()
        }
    }

    // Function to construct the URL of the image in Azure Blob Storage
    func getImageURL(storageAccountName: String, containerName: String, blobName: String, sasToken: String? = nil) -> URL? {
        // Construct the base URL
        var urlString = "https://\(storageAccountName).blob.core.windows.net/\(containerName)/\(blobName)"
    
        // Append the SAS token if provided
        if let token = sasToken {
            if token != "" {
                urlString += "?\(token)"
            }
        }
    
        return URL(string: urlString)
    }
}

Upvotes: 0

davidchai21
davidchai21

Reputation: 21

In iOS 11 and Swift 4, you can do like this:

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

This is just an example. Hope it helps.

Upvotes: 1

el_even
el_even

Reputation: 674

Here is a simple example.

1- Start here: https://azure.microsoft.com/en-us/documentation/articles/storage-ios-how-to-use-blob-storage/

2- Get the SDK

3- Here is the code:

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

Enjoy :)

Upvotes: 6

Chris Anderson
Chris Anderson

Reputation: 8515

You have to use their REST API, but they're working on an SDK right now.

There are a couple of examples of using their REST API on iOS. A cursory search brings up: Uploading to azure blob storage from SAS URL returns 404 status

There is also this example on Github - https://github.com/Ajayi13/BlobExample-Swift

Upvotes: 2

Related Questions