簡體   English   中英

上傳 SwiftUI 圖片到 Firebase with Data

[英]Upload SwiftUI Image to Firebase with Data

我在一個應用程序中創建簡單的 CRUD 操作,我遇到了一個毛茸茸的怪癖,考慮到 SwiftUI 的Image設計。

我正在嘗試將image上傳到 Firebase,但我需要將Image轉換為UIImage ,然后進一步轉換為Data

這是我的代碼:

圖片上傳器

import UIKit
import Firebase
import FirebaseStorage
import SwiftUI

struct ImageUploader {
    static func uploadImage(with image: Data, completion: @escaping(String) -> Void) {
        let imageData = image
        let fileName = UUID().uuidString
        let storageRef = Storage.storage().reference(withPath: "/profile_images/\(fileName)")
        storageRef.putData(imageData, metadata: nil) { (metadata, error) in
            if let error = error {
                print("Error uploading image to Firebase: \(error.localizedDescription)")
                return
            }
            print("Image successfully uploaded to Firebase!")
        }
        
        storageRef.downloadURL { url, error in
            guard let imageUrl = url?.absoluteString else { return }
            completion(imageUrl)
        }
    }
}


查看Model

import SwiftUI
import Firebase

 func uploadProfileImage(with image: Data) {
        guard let uid = tempCurrentUser?.uid else { return }
        let imageData = image
        ImageUploader.uploadImage(with: imageData) { imageUrl in
            Firestore.firestore().collection("users").document(uid).updateData(["profileImageUrl":imageUrl]) { _ in
                print("Successfully updated user data")
            }
        }
    }

圖片選擇器

import SwiftUI
import PhotosUI

@MainActor
class ImagePicker: ObservableObject {
    @Published var image: Image?
    
    @Published var imageSelection: PhotosPickerItem? {
        didSet {
            if let imageSelection {
                Task {
                    try await loadTransferrable(from: imageSelection)
                }
            }
        }
    }
    
    func loadTransferrable(from imageSelection: PhotosPickerItem?) async throws {
        do {
            if let data = try await imageSelection?.loadTransferable(type: Data.self) {
                if let uiimage = UIImage(data: data) {
                    self.image = Image(uiImage: uiimage)
                }
            }
        } catch {
            print("Error: \(error.localizedDescription)")
        }
    }
}


看法

 if let image = imagePicker.image {
                Button {
                    viewModel.uploadProfileImage(with: image)
                } label: {
                    Text("Continue")
                        .font(.headline)
                        .foregroundColor(.white)
                        .frame(width: 340.0, height: 50.0)
                        .background(.blue)
                        .clipShape(Capsule())
                        .padding()
                }
                .shadow(radius: 10.0)
                .padding(24.0)
            }

如您所見,我在視圖中遇到問題:無法將類型“Image”的值轉換為預期的參數類型“Data” ,這是有道理的。 這些圖像都是Data類型。

我該怎么做?

不要使用@Published var image: Image? 在您的class ImagePicker: ObservableObject中, Image是一個 View 並且用於其他Views

使用@Published var image: UIImage? 並相應地調整您的代碼。

然后使用image.pngData()獲取要上傳的Data

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM