Q&A
Swift初心者のヒロポメです。
Firebase関連でつまづいてしまったので、お助けください・・・
【やりたいこと】
Firebaseから複数の音声データを取得して、collection viewに表示させたいです。
【つまづき箇所】
FirebaseのStorageにはすでに複数音声をアップ済です。
それらを取得してcollection viewに1個1個表示させたいものの、
ビルドはできても、最新の音声しか流れません。collection viewのうち、どのcellを押しても、
同じ最新の1つの音声しか流れません。
以下コードのsnapshotをprintしてみると、確かに1メッセージ分の情報しか出力されません。
FirebaseのDatabase上の構造は以下の通りです。
Media_Messagesの下に、childByAutoId、その下にsender_id, sender_name, toID, urlなどがぶら下がっています。
![
どこをいじればやりたいことが実現できますでしょうか。
アドバイス頂けますととても助かります、、、
よろしくお願いいたします。
Swift
1 2 var audioPlayer: AVAudioPlayer! 3 4Database.database().reference.child("Media_Messages").observe(.childAdded, with:{ 5 (snapshot) in 6 7 print(snapshot) 8 /*出力結果: 9Snap (-L6tdyvGHT1hXnz34teV) { 10 "sender_id" = mZJKe7aV8gWMNZS0GHfwfh649Sh2; 11 "sender_name" = yeah; 12 toID = 555; 13 url = "https://firebasestorage.googleapis.com/v0/b/guy-4cc29.appspot.com/o/Audio_Storage%2FmZJKe7aV8gWMNZS0GHfwfh649Sh29F395AA3-A3EF-4612-AF25-9963E06B059D.m4a?alt=media&token=56ecd74b-0fee-4c17-b2a3-c290b73bdedc"; 14 } */ 15 16 if let dictionary2 = snapshot.value as? [String:AnyObject]{ 17 if let audioUrl = dictionary2["url"] as? String { 18 print(audioUrl) 19 //https://firebasestorage.googleapis.com/v0/b/guy-4cc29.appspot.com/o/Audio_Storage%2FmZJKe7aV8gWMNZS0GHfwfh649Sh29F395AA3-A3EF-4612-AF25-9963E06B059D.m4a?alt=media&token=56ecd74b-0fee-4c17-b2a3-c290b73bdedc 20 let url2 = URL(string: audioUrl) 21 print(url2) 22 //Optional(https://firebasestorage.googleapis.com/v0/b/guy-4cc29.appspot.com/o/Audio_Storage%2FmZJKe7aV8gWMNZS0GHfwfh649Sh29F395AA3-A3EF-4612-AF25-9963E06B059D.m4a?alt=media&token=56ecd74b-0fee-4c17-b2a3-c290b73bdedc) 23 24 URLSession.shared.dataTask(with: url2!, completionHandler: { (data, response, error) in 25 26 DispatchQueue.global().async{ 27 DispatchQueue.main.async{ 28 29 do { self.audioPlayer = try AVAudioPlayer(data:data!) 30 31 } 32 catch{} 33 34 } 35 } 36 37 }).resume() 38 } 39 } 40 } , withCancel:nil) 41 42 43//collectionviewで再生 44 func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { 45 do{ 46 audioPlayer.play() 47 } catch { 48 49 } 50 51 }
回答1件
あなたの回答
tips
プレビュー
下記のような回答は推奨されていません。
このような回答には修正を依頼しましょう。
2018/03/08 03:54
2018/03/08 08:04
2018/03/08 14:54
2018/03/08 21:23
2018/03/10 04:02 編集
2018/03/10 06:43 編集
2018/03/10 09:08
2018/03/10 11:00
2018/03/11 09:42