元数据?.downloadURL()?absoluteString

时间:2018-05-25 20:38:53

标签: swift firebase

我对旧语法有一些问题,如:

metadata?.downloadURL()?.absoluteString"

如何在我的代码中使用新方法? 此部分代码出错:

let downloadURL = metadata?.storageReference?.downloadURLWithCompletion()

完整代码:

Storage.storage().reference().child(imgUid).putData(imgData, metadata: metadata) { (metadata, error) in
    if error != nil {
        print("Did'n upload image")
    } else {
        print("uploaded")
        let downloadURL = metadata?.storageReference?.downloadURLWithCompletion()

        if let url = downloadURL {
            self.setUser(img: url)
        }
    }
}

2 个答案:

答案 0 :(得分:0)

这是一个简单的方法,使用此Func将数据保存到FirebaseStorage然后将URL作为字符串,然后您可以将其保存在

func uploadImageToFirebaseStorage(data: Data, onSuccess: @escaping (_ imageUrl: String) -> Void) {
    let photoIdString = NSUUID().uuidString
    let storageRef = Storage.storage().reference(forURL: Config.STORAGE_REF_URL).child(POST_REF).child(photoIdString)


    storageRef.putData(data, metadata: nil) { (metadata, error) in
        if let error = error {
            debugPrint(error.localizedDescription)
            return
        }

        metadata?.storageReference?.downloadURL(completion: { (url, error) in
            if let error = error {
                print(error.localizedDescription)
                return
            }
            onSuccess("\(url!)")
        })
    }
}

答案 1 :(得分:0)

func save() {
    let newPostRef = Database.database().reference().child("users").childByAutoId()
    let newPostKey = newPostRef.key

    // 1. save image
    if let imageData = self.profilPic!.jpegData(compressionQuality:0.5) {
        let storage = Storage.storage().reference().child("profileImages")
         DispatchQueue.main.sync {
        storage.putData(imageData).observe(.success, handler: { (snapshot) in
            storage.downloadURL(completion: { (url, error) in
                if error != nil {
                    print(error!.localizedDescription)
                    return
                }
                if let profileImageUrl = url?.absoluteString {
                    guard let uid = (Auth.auth().currentUser?.uid) else {return}
                    let values = ["name": self.name, "email": self.email, "profilePictureUrl": profileImageUrl]

                    newPostRef.setValue(values)
                    self.ref.child(uid).childByAutoId().setValue(values)

                    }
            })
            })

        }
    }
}