2016-12-03 51 views
-3

我想通過使用API​​Kit的iTu​​nes 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。

Realm沒有直接支持JSON,但可以使用NSJSONSerialization.JSONObjectWithData(_:options:)的輸出從JSON添加對象。生成的符合KVC的對象可用於使用標準API添加/更新對象以創建和更新對象。

瞭解更多https://realm.io/docs/swift/latest/#json