Не уверен, где в коде разместить storageRef.downloadURL - PullRequest
0 голосов
/ 19 февраля 2019

После обновления Firebase до версии 4 и исправления всех 200 ошибок у меня осталось 2 предупреждения, которые приводят к сбою моего приложения.Я посмотрел на эту ошибку и попытался разрешить ее безуспешно:

storageReference.downloadURLWithCompletion()

Я, должно быть, ошибаюсь:

func setUserInfo(_ user: User!, usersname: String, email: String, password: String, cell: String, data: Data!) {

    // Create Path for User Image
    let imagePath = "images/riders/\(user.uid)/Profile Pic/userPic.jpg"

    // Create image Reference
    let imageRef = rDataService.Instance.storageRef.child(imagePath)

    // Create Metadata for the image
    let metaData = StorageMetadata()
    metaData.contentType = "image/jpeg"

    // Save the user Image in the Firebase Storage File
    imageRef.putData(data as Data, metadata: metaData) { (metaData, error) in
        if error == nil {
            let changeRequest = user.createProfileChangeRequest()
            changeRequest.displayName = usersname
            changeRequest.photoURL = metaData?.downloadURL()
            changeRequest.commitChanges(completion: { (error) in

                if error == nil {
                    self.saveUser(user, usersname: usersname, email: email, password: password, cell: cell)

                } else {
                    print(error!.localizedDescription)
                }
            })

        } else {
            print(error!.localizedDescription)
        }
    }

}

Ошибка в этой строке:

changeRequest.photoURL = metaData?.downloadURL()

Редактировать

После корректировок появляется предупреждение в этой строке:

if let profilepicMetaData = profilepicMetaData {

error: Value 'profilepicMetaData' was defined but never used; consider  replacing with boolean test

Приложение все еще не работает:

// Save the user profile Image in the Firebase Storage File
    imageRef.putData(data as Data, metadata: profilepicMetaData) { (profilepicMetaData, error) in
        if let profilepicMetaData = profilepicMetaData {
            imageRef.downloadURL(completion: { (url, error) in

                guard let url = url else {
                    if let error = error {
                        print(error)
                    }
                    return
                }
                let changeRequest = user.createProfileChangeRequest()
                changeRequest.displayName = usersname
                changeRequest.photoURL = url

                changeRequest.commitChanges(completion: { (error) in

                if error == nil {
                    self.saveUser(user, usersname: usersname, email: email, password: password, year: year, makeAndModel: makeAndModel, cell: cell, plateNo: plateNo)

                } else {
                    print(error!.localizedDescription)
                }
            })
        })

        } else {
            print(error!.localizedDescription)
        }
    }

Crash!

crash screen shot

1 Ответ

0 голосов
/ 19 февраля 2019

Вам необходимо использовать исходный эталонный объект хранения imageRef, чтобы получить URL-адрес загрузки.(пожалуйста, проверьте комментарии через код):

imageRef.putData(data, metadata: profilepicMetaData) {
    // use if let to unwrap the metadata returned to make sure the upload was successful. You can use an underscore to ignore the result
    if let _ = $0 {
        // start the async method downloadURL to fetch the url of the file uploaded
        imageRef.downloadURL {
            // unwrap the URL to make sure it is not nil
            guard let url = $0 else {
                // if the URL is nil unwrap the error, print it 

                if let error = $1 { 
                    // you can present an alert with the error localised description
                    print(error) 
                }
                return
            }
            // your createProfileChangeRequest code  needs to be run after the download url method completes. If you place it after the closure it will be run before the async method finishes.
            let changeRequest = user.createProfileChangeRequest()
            changeRequest.displayName = usersname
            changeRequest.photoURL = url
            changeRequest.commitChanges {
                // unwrap the error and print it
                if let error = $0 {
                    // again you might present an alert with the error
                    print(error)
                } else {
                    // user was updated successfully
                    self.saveUser(user, usersname: usersname, email: email, password: password, year: year, makeAndModel: makeAndModel, cell: cell, plateNo: plateNo)
                }
            }
        }
    } else if let error = $1 {
        // present an alert with the error
        print(error)
    }
}
...