1
0

sample.swift.txt 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import Foundation
  2. protocol APIControllerProtocol {
  3. func didReceiveAPIResults(results: NSArray)
  4. }
  5. class APIController {
  6. var delegate: APIControllerProtocol
  7. init(delegate: APIControllerProtocol) {
  8. self.delegate = delegate
  9. }
  10. func get(path: String) {
  11. let url = NSURL(string: path)
  12. let session = NSURLSession.sharedSession()
  13. let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in
  14. println("Task completed")
  15. if(error != nil) {
  16. // If there is an error in the web request, print it to the console
  17. println(error.localizedDescription)
  18. }
  19. var err: NSError?
  20. if let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as? NSDictionary {
  21. if(err != nil) {
  22. // If there is an error parsing JSON, print it to the console
  23. println("JSON Error \(err!.localizedDescription)")
  24. }
  25. if let results: NSArray = jsonResult["results"] as? NSArray {
  26. self.delegate.didReceiveAPIResults(results)
  27. }
  28. }
  29. })
  30. // The task is just an object with all these properties set
  31. // In order to actually make the web request, we need to "resume"
  32. task.resume()
  33. }
  34. func searchItunesFor(searchTerm: String) {
  35. // The iTunes API wants multiple terms separated by + symbols, so replace spaces with + signs
  36. let itunesSearchTerm = searchTerm.stringByReplacingOccurrencesOfString(" ", withString: "+", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil)
  37. // Now escape anything else that isn't URL-friendly
  38. if let escapedSearchTerm = itunesSearchTerm.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) {
  39. let urlPath = "https://itunes.apple.com/search?term=\(escapedSearchTerm)&media=music&entity=album"
  40. }
  41. }
  42. }