2016-12-03 12 views
-3

APIKitを使用してiTunes APIで曲情報を取得し、Realmに保存したいと考えています。 しかし、次のコードを持つ "オブジェクト"の型はAnyです。要素の抽出方法はわかりません。 出力結果は次のとおりです。APIKitでiTunes APIから曲情報を取得したい

{ 
    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

まず、応答JSONを解析する必要があります。

レルムはJSONを直接サポートしていませんが、NSJSONSerialization.JSONObjectWithData(_:options:)の出力を使用してJSONからオブジェクトを追加することは可能です。生成されたKVC準拠オブジェクトは、オブジェクトの作成および更新のための標準APIを使用してオブジェクトを追加/更新するために使用できます。

https://realm.io/docs/swift/latest/#json

で詳細をご覧ください
関連する問題