Created
July 2, 2017 01:32
-
-
Save KrisYu/10764e91331b3ddd1dcab5efa1aa6d9d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Cocoa | |
import PlaygroundSupport | |
PlaygroundPage.current.needsIndefiniteExecution = true | |
struct iTunesRequestManager { | |
static func getSearchResult(_ query: String, results: Int, langString: String, completionHandler: @escaping ([[String: AnyObject]], NSError?) -> Void){ | |
var urlComponents = URLComponents.init(string: "https://itunes.apple.com/search") | |
let termQueryItem = URLQueryItem.init(name: "term", value: query) | |
let limitQueryItem = URLQueryItem.init(name: "limit", value: "\(results)") | |
let mediaQueryItem = URLQueryItem.init(name: "media", value: "music") | |
urlComponents?.queryItems = [termQueryItem, mediaQueryItem, limitQueryItem] | |
guard let url = urlComponents?.url else { | |
return | |
} | |
let task = URLSession.shared.dataTask(with: url) { (data, response, error) -> Void in | |
guard let data = data else { | |
completionHandler([], nil) | |
return | |
} | |
do { | |
guard let itunesData = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: AnyObject] else { | |
completionHandler([], nil) | |
return | |
} | |
if let results = itunesData["results"] as? [[String: AnyObject]] { | |
completionHandler(results, nil) | |
} else { | |
completionHandler([], nil) | |
} | |
} catch _ { | |
completionHandler([], error as NSError?) | |
} | |
} | |
task.resume() | |
} | |
} | |
iTunesRequestManager.getSearchResult("周杰伦", results: 2, langString: "zh_cn") { (result, error) in | |
dump(result) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment