我想使用APIKit通过iTunes API获取歌曲信息并将其保存到Realm。 但是,具有以下代码的“对象”类型是Any,我不知道如何提取元素。 这是输出结果。
{
resultCount = 10;
results = (
{
artistId = 298496035;
artistName = "\U30a2\U30f4\U30a3\U30fc\U30c1\U30fc";
artistViewUrl = "https://itunes.apple.com/jp/artist/avu-ichi/id298496035?uo=4";
artworkUrl100 = "http://is1.mzstatic.com/image/thumb/Music4/v4/0e/c9/c8/0ec9c862-abdd-8827-9b0d-c30443a88e86/source/100x100bb.jpg";
・・・
请告诉我如何从此输出结果中提取歌曲信息的元素。
import APIKit
protocol iTunesRequest: Request {
}
extension iTunesRequest {
var baseURL: URL {
return URL(string: "http://itunes.apple.com")!
}
}
struct GetSearchRequest: iTunesRequest {
typealias Response = [Song]
var method: HTTPMethod {
return .get
}
let term: String
init(term: String) {
self.term = term
}
var path: String {
return "/search"
}
var parameters: Any? {
return [
"term": term,
"limit": 10,
"country": "jp",
"media": "music",
"lang": "ja_jp"
]
}
func response(from object: Any, urlResponse: HTTPURLResponse) throws -> Response {
var Songs = [Song]()
print(object)
if let dictionaries = object as? [NSDictionary] {
print(dictionaries)
for dictionary in dictionaries {
print(dictionary)
let song = Song()
song.itunesId = dictionary["trackId"] as! Int
song.title = dictionary["trackName"] as! String
song.artwork = dictionary["artworkUrl100"] as! String
song.artist = dictionary["artistName"] as! String
song.album = dictionary["collectionName"] as! String
song.trackSource = dictionary["previewUrl"] as! String
Songs.append(song)
}
}
return Songs
}
}
答案 0 :(得分:0)
您需要先解析响应JSON。
了解详情Realm没有直接支持JSON,但可以使用
NSJSONSerialization.JSONObjectWithData(_:options:)
的输出从JSON添加对象。生成的符合KVC的对象可用于使用标准API添加/更新对象,以创建和更新对象。