Ajay
Ajay

Reputation: 1622

How to use the blob storage service from ios?

In my application I need to use the Windows Azure services to store the data for that I am using this:http://www.windowsazure.com/en-us/develop/mobile/tutorials/get-started-with-data-ios/ sdk for Windows azure integration from my app. Now I need to upload the images to Azure and for that I was using the same sdk...But later I found that the right place in Windows Azure to upload the larger images is to Blob Storage Client.

In .Net they have the different library and I found this link http://www.windowsazure.com/en-us/develop/net/how-to-guides/blob-storage/ for uploading the images to blob storage.

But how can I do that with Objective C?

After some research I found this link http://www.deviantpoint.com/post/2012/02/18/Using-Azure-Storage-Services-from-an-iPhone-App-Part-1-Table-and-Blob-setup-Azure-iOS-toolkit-and-Model-Classes.aspx but its not clear about How to upload an image and getting the image url in response?

Upvotes: 12

Views: 7385

Answers (4)

Shakeel Ahmed
Shakeel Ahmed

Reputation: 6023

Swift 5+ 100% Working Easy Solution its sweet for you all after struggling a half day just copy paste in your controller easy to use

//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

Chris Prince
Chris Prince

Reputation: 7574

See the following https://github.com/crspybits/Blobbish for an Azure Objective-C example in a non-SAS style.

Upvotes: 0

Ajay
Ajay

Reputation: 1622

After a lots of R&D...I finally found the solution..

Here is my sample project Blob Example written in Objective C

& also tried with Swift & is working as expected. Here is my Swift Example Project.

Just replace your account credentials with respective ones and you are good to go..!!

Note: Try to use UIImageJPEGRepresentation instead of UIImagePNGRepresentation because png takes more size than jpg.

Upvotes: 15

jaggo
jaggo

Reputation: 1

REST API maybe better for iOS devices. Azure SDK does not have object-c support as good as C# I am afraid.

http://msdn.microsoft.com/en-us/library/windowsazure/dd135733.aspx

Upvotes: 0

Related Questions