使用Firebase上传图片& Swift(iOS)

时间:2018-01-16 11:06:52

标签: ios swift firebase firebase-storage uploading

在开始之前,我想预先警告我的代码很可能不正确,因为我是Swift编码的初学者。

我正在为一个大学项目创建一个应用程序,它是我创建的第一个大型应用程序,而且我没有编写很长时间。

我在使用firebase创建帐户时尝试上传图像时出现问题,我之前已经使用了代码,但我正在使用'childByAutoId()'写入数据库,但工作正常,但我意识到我需要写入数据库并通过用户ID保存它。在我将'childByAutoId()'更改为'child(uid)'后,这是我用户ID的前缀变量,它停止上传图像,我无法弄清楚原因。我曾尝试回到使用childByAutoId()的时候,但是现在它也没有用。

我的代码:

import UIKit
import Firebase
import FirebaseStorage

class RegisterViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

@IBOutlet weak var profileImage: UIImageView!
@IBOutlet weak var usernameField: UITextField!
@IBOutlet weak var emailField: UITextField!
@IBOutlet weak var passwordField: UITextField!
@IBOutlet weak var dobField: UITextField!
@IBOutlet weak var selectImageButton: UIButton!

var imageFileName = ""

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.

    self.view.addGestureRecognizer(UITapGestureRecognizer(target: self.view, action: #selector(UIView.endEditing(_:))))

    let datePicker = UIDatePicker()
    datePicker.datePickerMode = UIDatePickerMode.date
    datePicker.addTarget(self, action: #selector(RegisterViewController.datePickerValueChanged(sender:)), for: UIControlEvents.valueChanged)
    dobField.inputView = datePicker

    self.profileImage.layer.cornerRadius = self.profileImage.frame.size.width / 2;
    self.profileImage.clipsToBounds = true;

}

@objc func datePickerValueChanged(sender: UIDatePicker) {
    let formatter = DateFormatter()
    formatter.dateStyle = DateFormatter.Style.medium
    formatter.timeStyle = DateFormatter.Style.none
    dobField.text = formatter.string(from: sender.date)
}


@IBAction func selectImageTapped(_ sender: UIButton) {
    let picker = UIImagePickerController()
    picker.delegate = self
    self.present(picker, animated: true, completion: nil)
}

func uploadImage(image: UIImage) {
    let randomName = randomStringWithLength(length: 10)
    let imageData = UIImageJPEGRepresentation(image, 1.0)
    let uploadRef = Storage.storage().reference().child("images/profimg/\(randomName).jpg")
    let uploadTask = uploadRef.putData(imageData!, metadata: nil) { metadata,
        error in
        if error == nil {
            //success
            print("success")
            self.imageFileName = "\(randomName as String).jpg"
        } else {
            //error
            print("error uploading image")
        }
    }
}

func randomStringWithLength(length: Int) -> NSString {
    let characters: NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    let randomString: NSMutableString = NSMutableString(capacity: length)

    for i in 0..<length {
        var len = UInt32(characters.length)
        var rand = arc4random_uniform(len)
        randomString.appendFormat("%C", characters.character(at: Int(rand)))
    }
    return randomString
}

func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
    // will run if the user hits cancel
    picker.dismiss(animated: true, completion: nil)
}

@objc func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    // will run when the user finishes picking an image from the library
    if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
        self.profileImage.image = pickedImage
        self.selectImageButton.isEnabled = false
        self.selectImageButton.isHidden = true
        uploadImage(image: pickedImage)
        picker.dismiss(animated: true, completion: nil)
    }
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func registerTapped(_ sender: UIButton) {

    let username = usernameField.text
    let email = emailField.text
    let password = passwordField.text
    let dob = dobField.text

    Auth.auth().createUser(withEmail: email!, password: password!) { (user, error) in
        if error != nil {
            //error creating account
            let alert = UIAlertController(title: "Error", message: "An error occurred when creating your account, please try again.", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
            self.present(alert, animated: true, completion: nil)
        }else {
            //account created

            if (self.imageFileName != "") {
                if let uid = Auth.auth().currentUser?.uid {

                    let regObject: Dictionary<String, Any> = [
                        "uid" : uid,
                        "username" : username,
                        "dateofbirth" : dob,
                        "profimage" : self.imageFileName
                    ]
                Database.database().reference().child("posts").child(uid).setValue(regObject)

                    let vc = self.storyboard?.instantiateViewController(withIdentifier: "LoggedInVC")
                    self.present(vc!, animated: true, completion: nil)
                }else {
                    //image hasnt finished uploading
                    let alert = UIAlertController(title: "Please wait", message: "Your image has not finished uploading yet, please wait...", preferredStyle: .alert)
                    alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
                    self.present(alert, animated: true, completion: nil)
                }
            }

            //let alert = UIAlertController(title: "Success!", message: "Account has been created...", preferredStyle: .alert)
            //alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
            //self.present(alert, animated: true, completion: nil)

        }
    }
}

/*
// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
}
*/

}

如果你们中的任何一个人能指出我正确的方向,或者能够在我的代码中向我展示出错的地方,那就太棒了。我不期望直接解决我的问题所以任何事情都会有所帮助。

谢谢!

2 个答案:

答案 0 :(得分:1)

在firebase存储上上传img

func uploadImagePic(img1 :UIImage){
        var data = NSData()
        data = UIImageJPEGRepresentation(img1!, 0.8)! as NSData
        // set upload path
        let filePath = "\(userid)" // path where you wanted to store img in storage
        let metaData = FIRStorageMetadata()
        metaData.contentType = "image/jpg"

        self.storageRef = FIRStorage.storage().reference()
        self.storageRef.child(filePath).put(data as Data, metadata: metaData){(metaData,error) in
            if let error = error {
                print(error.localizedDescription)
                return
            }else{
                //store downloadURL
                let downloadURL = metaData!.downloadURL()!.absoluteString

            }
        }

    }

答案 1 :(得分:0)

为了从上传的文件中获取下载URL,基于答案,现在不推荐使用metaData中的downloadURL,因此这是正确的方法:

 storageRef.downloadURL(completion: { (url: URL?, error: Error?) in
    print(url?.absoluteString) // <- Your url
 })

您应该从刚刚创建的参考中获取下载网址,在这里可以找到带有完成处理程序的downloadURL

这是更新的Swift 5答案:

func uploadImagePic(image: UIImage, name: String, filePath: String) {
    guard let imageData: Data = image.jpegData(compressionQuality: 0.1) else {
        return
    }

    let metaDataConfig = StorageMetadata()
    metaDataConfig.contentType = "image/jpg"

    let storageRef = Storage.storage().reference(withPath: filePath)

    storageRef.putData(imageData, metadata: metaDataConfig){ (metaData, error) in
        if let error = error {
            print(error.localizedDescription)

            return
        }

        storageRef.downloadURL(completion: { (url: URL?, error: Error?) in
            print(url?.absoluteString) // <- Download URL
        })
    }
}