如何解决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字符串。
func getNowPlayingView(completion: @escaping (String) -> Void){
completion(MusicPlayer.JN)
}
更新
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 举报,一经查实,本站将立刻删除。