Swift 4将图像上传到Firebase

时间:2017-10-28 13:15:43

标签: firebase xcode9 swift4

大家下午好,我正在尝试将图片上传到firebase并显示回一个单元格。我几乎所有内容都在工作,除了图像(我无法摆脱错误)。

Here is the error I am getting

  

无法为类型'帖子'调用初始值设定项使用类型'的参数列表(postImageStringUrl:String,content:String!,postId:String)'

    //[Save Image]
    // Create data in the server
    let data = UIImageJPEGRepresentation(self.addedImage.image!, 0.5)
    let metadata = StorageMetadata()
    metadata.contentType = "image/jpeg"

    let postId = "\(Auth.auth().currentUser!.uid)\(NSUUID().uuidString)"
   // Create a reference to the file you want to upload
    let imagePath = "postImages\(postId)/postPic.jpg"

    storageRef.child(imagePath).putData(data!, metadata: metadata) { (metadata, error) in
        if error == nil {
            let postRef = self.databaseRef.child("posts").childByAutoId()
            let post = Posts(postImageStringUrl: String (describing: metadata!.downloadURL()), content: descriptionTextView.text, postId: postId)
            postRef.setValue(post.toAnyObject())
        }else{
            print(error.debugDescription)
        }
    }
    //[Save Image]

这是我的postViewController

import Foundation
import Firebase
import FirebaseDatabase
import FirebaseStorage

struct Posts {

var postImageStringUrl: String! var department: String! var content: String! var username: String! var postId: String! var ref: DatabaseReference? var key: String! init(postImageStringUrl: String, department: String, content: String, username: String,postId: String, key: String = ""){ self.postImageStringUrl = postImageStringUrl self.department = department self.content = content self.username = username self.postId = postId self.key = key self.ref = Database.database().reference() } init(snapshot: DataSnapshot){ let snapshotValue = snapshot.value as! NSMutableDictionary self.postImageStringUrl = snapshotValue["postImageStringUrl"] as! String self.department = snapshotValue["department"] as! String self.content = snapshotValue["content"] as! String self.username = snapshotValue["username"] as! String self.postId = snapshotValue["postId"] as! String self.key = snapshot.key self.ref = snapshot.ref } func toAnyObject() -> [String: AnyObject] { return ["postImageStringUrl": postImageStringUrl as AnyObject, "department": department as AnyObject,"content": content as AnyObject,"username": username as AnyObject, "postId": postId as AnyObject] }

}

任何帮助将不胜感激...... Ty

1 个答案:

答案 0 :(得分:0)

您的帖子初始化

init(
   postImageStringUrl: String,
   department: String, 
   content: String, 
   username: String,
   postId: String, 
   key: String = "")

似乎您正在尝试使用

进行初始化
let post = Posts(
          postImageStringUrl: String (describing: metadata!.downloadURL()), 
          content: descriptionTextView.text, 
          postId: postId)

基本上只是在初始化中遗漏了几个参数;部门,用户名