-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGenreTableViewController.swift
More file actions
235 lines (180 loc) · 8.45 KB
/
GenreTableViewController.swift
File metadata and controls
235 lines (180 loc) · 8.45 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
//
// GenreTableViewController.swift
// MyFavoriteMovies
//
// Created by Jarrod Parkes on 1/23/15.
// Copyright (c) 2015 Udacity. All rights reserved.
//
import UIKit
// MARK: GenreTableViewController: UITableViewController
class GenreTableViewController: UITableViewController {
// MARK: Properties
var appDelegate: AppDelegate!
var session: NSURLSession!
var movies: [Movie] = [Movie]()
var genreID: Int? = nil
// MARK: Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
/* Get the app delegate */
appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
/* Get the shared URL session */
session = NSURLSession.sharedSession()
/* Get the correct genre id */
genreID = getGenreIDFromItemTag(self.tabBarItem.tag)
/* Create and set the logout button */
self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Reply, target: self, action: "logoutButtonTouchUp")
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
/* TASK: Get movies by a genre id, then populate the table */
/* 1. Set the parameters */
let methodParameters = [
"api_key": appDelegate.apiKey,
]
/* 2. Build the URL */
let urlString = appDelegate.baseURLSecureString + "genre/\(genreID!)/movies" + appDelegate.escapedParameters(methodParameters)
let url = NSURL(string: urlString)!
/* 3. Configure the request */
let request = NSMutableURLRequest(URL: url)
request.addValue("application/json", forHTTPHeaderField: "Accept")
/* 4. Make the request */
let task = session.dataTaskWithRequest(request) { (data, response, error) in
/* GUARD: Was there an error? */
guard (error == nil) else {
print("There was an error with your request: \(error)")
return
}
/* GUARD: Did we get a successful 2XX response? */
guard let statusCode = (response as? NSHTTPURLResponse)?.statusCode where statusCode >= 200 && statusCode <= 299 else {
if let response = response as? NSHTTPURLResponse {
print("Your request returned an invalid response! Status code: \(response.statusCode)!")
} else if let response = response {
print("Your request returned an invalid response! Response: \(response)!")
} else {
print("Your request returned an invalid response!")
}
return
}
/* GUARD: Was there any data returned? */
guard let data = data else {
print("No data was returned by the request!")
return
}
/* 5. Parse the data */
let parsedResult: AnyObject!
do {
parsedResult = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)
} catch {
parsedResult = nil
print("Could not parse the data as JSON: '\(data)'")
return
}
/* GUARD: Did TheMovieDB return an error? */
guard (parsedResult.objectForKey("status_code") == nil) else {
print("TheMovieDB returned an error. See the status_code and status_message in \(parsedResult)")
return
}
/* GUARD: Is the "results" key in parsedResult? */
guard let results = parsedResult["results"] as? [[String : AnyObject]] else {
print("Cannot find key 'results' in \(parsedResult)")
return
}
/* 6. Use the data! */
self.movies = Movie.moviesFromResults(results)
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
}
}
/* 7. Start the request */
task.resume()
}
// MARK: UITableViewController
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
/* Get cell type */
let cellReuseIdentifier = "MovieTableViewCell"
let movie = movies[indexPath.row]
let cell = tableView.dequeueReusableCellWithIdentifier(cellReuseIdentifier) as UITableViewCell!
/* Set cell defaults */
cell.textLabel!.text = movie.title
cell.imageView!.image = UIImage(named: "Film Icon")
cell.imageView!.contentMode = UIViewContentMode.ScaleAspectFit
/* TASK: Get the poster image, then populate the image view */
if let posterPath = movie.posterPath {
/* 1. Set the parameters */
// There are none...
/* 2. Build the URL */
let baseURL = NSURL(string: appDelegate.config.baseImageURLString)!
let url = baseURL.URLByAppendingPathComponent("w154").URLByAppendingPathComponent(posterPath)
/* 3. Configure the request */
let request = NSURLRequest(URL: url)
/* 4. Make the request */
let task = session.dataTaskWithRequest(request) { (data, response, error) in
/* GUARD: Was there an error? */
guard (error == nil) else {
print("There was an error with your request: \(error)")
return
}
/* GUARD: Did we get a successful 2XX response? */
guard let statusCode = (response as? NSHTTPURLResponse)?.statusCode where statusCode >= 200 && statusCode <= 299 else {
if let response = response as? NSHTTPURLResponse {
print("Your request returned an invalid response! Status code: \(response.statusCode)!")
} else if let response = response {
print("Your request returned an invalid response! Response: \(response)!")
} else {
print("Your request returned an invalid response!")
}
return
}
/* GUARD: Was there any data returned? */
guard let data = data else {
print("No data was returned by the request!")
return
}
/* 5. Parse the data */
// No need, the data is already raw image data.
/* 6. Use the data! */
if let image = UIImage(data: data) {
dispatch_async(dispatch_get_main_queue()) {
cell.imageView!.image = image
}
} else {
print("Could not create image from \(data)")
}
}
/* 7. Start the request */
task.resume()
}
return cell
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return movies.count
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
/* Push the movie detail view */
let controller = self.storyboard!.instantiateViewControllerWithIdentifier("MovieDetailViewController") as! MovieDetailViewController
controller.movie = movies[indexPath.row]
self.navigationController!.pushViewController(controller, animated: true)
}
// MARK: Logout
func logoutButtonTouchUp() {
self.dismissViewControllerAnimated(true, completion: nil)
}
}
// MARK: - Genre Map
extension GenreTableViewController {
/* Helper function: Uses the tab bar item tag to return the correct genre id */
func getGenreIDFromItemTag(itemTag: Int) -> Int {
let genres: [String] = [
"Sci-Fi",
"Comedy",
"Action"
]
let genreMap: [String:Int] = [
"Action": 28,
"Sci-Fi": 878,
"Comedy": 35
]
return genreMap[genres[itemTag]]!
}
}