Закрытие с помощью FirebaseStorage (UIImage → URL) - PullRequest
0 голосов
/ 19 сентября 2018

Я создаю новый процесс регистрации с использованием Firebase Auth / Storage / Firestore.

Вот процесс новой регистрации (сначала выполните аутентификацию с помощью Auth, зарегистрируйте возвращенного пользователя в Firestore, сохраните URL-адрес, если он есть).изображение) процесса.

static func signUp(name: String, email: String, password: String, image: UIImage?, onSuccess: @escaping () -> Void, onError: @escaping (_ errorMessage: String?) -> Void) {
    Auth.auth().createUser(withEmail: email, password: password, completion: { user, error in
        if error != nil {
            onError(error)
            return
        }
        guard let uid = user?.user.uid else { return }
        var dict: [String: Any] = [
            "name": name,
            "email": email
        ]
        // If Image is Set
        if let image = image {
            StorageService.storage(image: image, path: .icon, id: uid) { (imageUrl) in
                dict["iconUrl"] = imageUrl
            }
        }
        Firestore.firestore().collection("users").document(uid).setData(dict) { (error) in
            if let error = error {
                print(error)
                return
            }
        }
        onSuccess()
    })
}

Ниже приведена функция получения UIImage хранилища в качестве аргумента и возврата класса URL StorageService {

// Upload Image to Storage
static func storage(image: UIImage?, path: PathType, id: String, completion: @escaping (_ imageUrl: String?) -> ()) {
    guard let image = image, let imageData = UIImageJPEGRepresentation(image, 0.1) else {
        print("Non Image")
        completion(nil)
        return
    }
    let storageRef = Storage.storage().reference().child(path.rawValue).child(id)
    storageRef.putData(imageData, metadata: nil, completion: { (metaData, error) in
        if let error = error {
            print("Fail to Put Data in Storage : \(error)")
            completion(nil)
            return
        }
        storageRef.downloadURL { (imageUrl, error) in
            if let error = error {
                print("Fail to Download Url : \(error)")
                completion(nil)
                return
            }
            if let imageUrl = imageUrl?.absoluteString {
                completion(imageUrl)
            }
        }
    })
}

}

Регистрация Auth и сохранение в FireStore выполнены успешно, но при наличии изображения, хотя оно и хранится в хранилище, URL-адрес изображения не сохраняется в Firestore.

storage () Есть ли проблема скак написать закрытие?

1 Ответ

0 голосов
/ 19 сентября 2018

Функция StorageService.storage является асинхронной, при наличии изображения функция для вставки в хранилище выполняется без получения ответа URL.Вы должны поместить свою функцию для вставки в clousure StorageService.storage, чтобы получить и сохранить URL-адрес изображения

// If Image is Set
    if let image = image {
      StorageService.storage(image: image, path: .icon, id: uid) { (imageUrl) in
          dict["iconUrl"] = imageUrl
          Firestore.firestore().collection("users").document(uid).setData(dict) { (error) in
              if let error = error {
                  print(error)
                  return
              }
              onSuccess()
          }
      }
    }else {
      Firestore.firestore().collection("users").document(uid).setData(dict) { (error) in
          if let error = error {
              print(error)
              return
          }
          onSuccess()
      }
    }
...