-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApiService.swift
executable file
·59 lines (40 loc) · 1.84 KB
/
ApiService.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
//
// ApiService.swift
// youtube
//
// Created by Brian Voong on 6/30/16.
// Copyright © 2016 letsbuildthatapp. All rights reserved.
//
import UIKit
class ApiService: NSObject {
static let sharedInstance = ApiService()
func fetchVideos(_ completion: @escaping ([Video]) -> ()) {
let url = URL(string: "https://s3-us-west-2.amazonaws.com/youtubeassets/home.json")
URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in
if error != nil {
print(error)
return
}
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers)
var videos = [Video]()
for dictionary in json as! [[String: AnyObject]] {
let video = Video()
video.title = dictionary["title"] as? String
video.thumbnailImageName = dictionary["thumbnail_image_name"] as? String
let channelDictionary = dictionary["channel"] as! [String: AnyObject]
let channel = Channel()
channel.name = channelDictionary["name"] as? String
channel.profileImageName = channelDictionary["profile_image_name"] as? String
video.channel = channel
videos.append(video)
}
DispatchQueue.main.async(execute: {
completion(videos)
})
} catch let jsonError {
print(jsonError)
}
}) .resume()
}
}