Swift JSON编码和解码

问题描述

我正在尝试将JSON返回完成状态:

func getNowPlayingView(completion: @escaping ([NowPlayingData]) -> ()) {
         
        
        
        let podcast = try! JSONDecoder().decode(MusicPlayer.NowPlayingData.self,from: Data(MusicPlayer.JN.utf8))
      
                       //print(data!)
                      // let episode = podcast.programs
                      dispatchQueue.main.async{
                          // The array is stored under programs Now
                       
                        completion(podcast)
                      }
         
    }

但是在completion(podcast)上,我得到Cannot convert value of type 'MusicPlayer.NowPlayingData' to expected argument type '[MusicPlayer.NowPlayingData]'

struct NowPlayingData: Codable,Identifiable {
    var id = UUID()
    var artist : String
    var song : String
    var cover : String
}

这是我的工作

您可以在屏幕快照中看到它正在向视图发送JSON字符串。

add image

要做代码

func getNowPlayingView(completion: @escaping (String) -> Void){
         
        
        
      
           completion(MusicPlayer.JN)
     
    }

更新

略微更改了代码以反映各种评论,我的观点发疯了

MediaPLAYER VIEW

struct MediaPlayerView: View {
    @State private var uuid = UIDevice.current.identifierForvendor?.uuidString
    @State private var playingtye = ""
    @State var NowPlayingInfo: [MusicPlayer.NowPlayingData]
    
    
    
    
    
    @State private var playing = ""
    var body: some View {
        vstack{
            Text(String(uuid!))
            Text(playingtye)
            Text(NowPlayingInfo.first!.artist)
            Text(playing)
        }
            .onAppear{
                Timer.scheduledTimer(withTimeInterval: 2.0,repeats: true) { (timer) in
                       // do stuff 42 seconds later
                                    MusicPlayer().gettype { type in
                                       self.playingtye = type
                                   }
                                    MusicPlayer().getNowPlayingView { (podcast) in
                                        self.NowPlayingInfo = podcast
                                    }
                   }
               
                
                if(MusicPlayer.shared.player!.rate != 0)
                {
                    self.playing = "yes"
                }
                else
                {
                    self.playing = "no"
                }
        }
          
    }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)