7

だから私は初めてFirebaseを使用しています。ビデオをストレージに保存してから、その一意の URL をデータベースに保存する必要があることを読みました。このアプローチをどのように採用しますか?たとえば、ユーザーが特定の動画の再生をリクエストした場合、データベースから URL を取得し、その URL を使用してデータベースから動画を取得するにはどうすればよいでしょうか?

助けてくれてありがとう。Firebase の経験がないことを許してください。

4

2 に答える 2

3

Google I/O でのゼロからアプリへのトークから、次のコードが出てきます。

// pragma mark - UIImagePickerDelegate overrides
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {

  // Get local file URLs
  guard let image: UIImage = info[UIImagePickerControllerOriginalImage] as? UIImage else { return }
  let imageData = UIImagePNGRepresentation(image)!
  guard let imageURL: NSURL = info[UIImagePickerControllerReferenceURL] as? NSURL else { return }

  // Get a reference to the location where we'll store our photos
  let photosRef = storage.reference().child("chat_photos")

  // Get a reference to store the file at chat_photos/<FILENAME>
  let photoRef = photosRef.child("\(NSUUID().UUIDString).png")

  // Upload file to Firebase Storage
  let metadata = FIRStorageMetadata()
  metadata.contentType = "image/png"
  photoRef.putData(imageData, metadata: metadata).observeStatus(.Success) { (snapshot) in
    // When the image has successfully uploaded, we get it's download URL
    let text = snapshot.metadata?.downloadURL()?.absoluteString
    // Set the download URL to the message box, so that the user can send it to the database
    self.messageTextField.text = text
  }

  // Clean up picker
  dismissViewControllerAnimated(true, completion: nil)
}

これは、画像ピッカーで選択された画像を取得し、それを Firebase Storage にアップロードしてから、その画像の結果のダウンロード URL をテキスト フィールドに設定します。

// Send a chat message
func sendMessage(sender: AnyObject) {
  // Create chat message
  let chatMessage = ChatMessage(name: self.username, message: messageTextField.text!, image: nil)
  messageTextField.text = ""

  // Create a reference to our chat message
  let chatRef = database.reference().child("chat")

  // Push the chat message to the database
  chatRef.childByAutoId().setValue(["name": chatMessage.name, "message": chatMessage.message])
}

次に、このsendMessageメソッドは、テキスト ボックスからデータベースにテキストを送信します。

その最小限の例の完全なコードは、この要点にあります。

于 2016-06-18T21:46:44.960 に答える
2

ビデオをFirebase Storageに保存するための私のソリューションは次のとおりです。スイフト3用。

func uploadVideo(_ path: URL, _ userID: String,
                 metadataEsc: @escaping (URL, FIRStorageReference)->(),
                 progressEsc: @escaping (Progress)->(),
                 completionEsc: @escaping ()->(),
                 errorEsc: @escaping (Error)->()) {

    let localFile: URL = path
    let videoName = getName()
    let nameRef = StorageHandler.videosRef.child(userID).child(videoName)
    let metadata = FIRStorageMetadata()
    metadata.contentType = "video"

    let uploadTask = nameRef.putFile(localFile, metadata: metadata) { metadata, error in
        if error != nil {
            errorEsc(error!)
        } else {
            if let meta = metadata {
                if let url = meta.downloadURL() {
                    metadataEsc(url, nameRef)
                }
            }
        }
    }

    _ = uploadTask.observe(.progress, handler: { snapshot in
        if let progressSnap = snapshot.progress {
            progressEsc(progressSnap)
        }
    })

    _ = uploadTask.observe(.success, handler: { snapshot in
        if snapshot.status == .success {
            uploadTask.removeAllObservers()
            completionEsc()  
        }
    })
}

func getName() -> String {
        let dateFormatter = DateFormatter()
        let dateFormat = "yyyyMMddHHmmss"
        dateFormatter.dateFormat = dateFormat
        let date = dateFormatter.string(from: Date())
        let name = date.appending(".mp4")
        return name
    }

呼び出し元:

StorageHandler.shared.uploadVideo(myFileURL, myUserID, metadataEsc: { (url, ref) in
    print("url = \(url)") // here is the URL you can then store into your Firebase tree
    print("ref = \(ref)")
}, progressEsc: { progress in
    print("progress = \(progress)")
}, completionEsc: {
    print("done")
}, errorEsc: { error in
    print("*** Error during file upload: \(error.localizedDescription)")
})
于 2016-12-06T07:49:13.583 に答える