Skip to content

Commit 069db5e

Browse files
committed
Part7
1 parent 11d589f commit 069db5e

File tree

8 files changed

+244
-27
lines changed

8 files changed

+244
-27
lines changed

SwiftTutorial.xcodeproj/project.pbxproj

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@
1616
020BE46F19A7265F006C3E0B /* Blank52.png in Resources */ = {isa = PBXBuildFile; fileRef = 020BE46E19A7265F006C3E0B /* Blank52.png */; };
1717
0262C60619A729E6003CF464 /* Album.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0262C60519A729E6003CF464 /* Album.swift */; };
1818
0262C60819A72A94003CF464 /* DetailsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0262C60719A72A94003CF464 /* DetailsViewController.swift */; };
19+
0262C60A19A73128003CF464 /* Track.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0262C60919A73128003CF464 /* Track.swift */; };
20+
0262C60C19A7321B003CF464 /* TrackCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0262C60B19A7321B003CF464 /* TrackCell.swift */; };
1921
/* End PBXBuildFile section */
2022

2123
/* Begin PBXContainerItemProxy section */
@@ -42,6 +44,8 @@
4244
020BE46E19A7265F006C3E0B /* Blank52.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = Blank52.png; sourceTree = "<group>"; };
4345
0262C60519A729E6003CF464 /* Album.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Album.swift; sourceTree = "<group>"; };
4446
0262C60719A72A94003CF464 /* DetailsViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DetailsViewController.swift; sourceTree = "<group>"; };
47+
0262C60919A73128003CF464 /* Track.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Track.swift; sourceTree = "<group>"; };
48+
0262C60B19A7321B003CF464 /* TrackCell.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TrackCell.swift; sourceTree = "<group>"; };
4549
/* End PBXFileReference section */
4650

4751
/* Begin PBXFrameworksBuildPhase section */
@@ -92,6 +96,8 @@
9296
020BE44D19A71EB3006C3E0B /* Supporting Files */,
9397
0262C60519A729E6003CF464 /* Album.swift */,
9498
0262C60719A72A94003CF464 /* DetailsViewController.swift */,
99+
0262C60919A73128003CF464 /* Track.swift */,
100+
0262C60B19A7321B003CF464 /* TrackCell.swift */,
95101
);
96102
path = SwiftTutorial;
97103
sourceTree = "<group>";
@@ -221,11 +227,13 @@
221227
isa = PBXSourcesBuildPhase;
222228
buildActionMask = 2147483647;
223229
files = (
230+
0262C60C19A7321B003CF464 /* TrackCell.swift in Sources */,
224231
020BE45219A71EB3006C3E0B /* SearchResultsViewController.swift in Sources */,
225232
020BE45019A71EB3006C3E0B /* AppDelegate.swift in Sources */,
226233
020BE46D19A721FF006C3E0B /* APIController.swift in Sources */,
227234
0262C60619A729E6003CF464 /* Album.swift in Sources */,
228235
0262C60819A72A94003CF464 /* DetailsViewController.swift in Sources */,
236+
0262C60A19A73128003CF464 /* Track.swift in Sources */,
229237
);
230238
runOnlyForDeploymentPostprocessing = 0;
231239
};

SwiftTutorial/APIController.swift

Lines changed: 26 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,27 @@ class APIController {
2020
self.delegate = delegate
2121
}
2222

23+
func get(path: String) {
24+
let url = NSURL(string: path)
25+
let session = NSURLSession.sharedSession()
26+
let task = session.dataTaskWithURL(url, completionHandler: {data, response, error -> Void in
27+
println("Task completed")
28+
if(error != nil) {
29+
// If there is an error in the web request, print it to the console
30+
println(error.localizedDescription)
31+
}
32+
var err: NSError?
33+
var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary
34+
if(err != nil) {
35+
// If there is an error parsing JSON, print it to the console
36+
println("JSON Error \(err!.localizedDescription)")
37+
}
38+
let results: NSArray = jsonResult["results"] as NSArray
39+
self.delegate.didReceiveAPIResults(jsonResult) // THIS IS THE NEW LINE!!
40+
})
41+
task.resume()
42+
}
43+
2344
func searchItunesFor(searchTerm: String) {
2445

2546
// The iTunes API wants multiple terms separated by + symbols, so replace spaces with + signs
@@ -28,28 +49,12 @@ class APIController {
2849
// Now escape anything else that isn't URL-friendly
2950
if let escapedSearchTerm = itunesSearchTerm.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) {
3051
let urlPath = "https://itunes.apple.com/search?term=\(escapedSearchTerm)&media=music&entity=album"
31-
let url: NSURL = NSURL(string: urlPath)
32-
let session = NSURLSession.sharedSession()
33-
let task = session.dataTaskWithURL(url, completionHandler: {data, response, error -> Void in
34-
println("Task completed")
35-
if(error != nil) {
36-
// If there is an error in the web request, print it to the console
37-
println(error.localizedDescription)
38-
}
39-
var err: NSError?
40-
41-
var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary
42-
if(err != nil) {
43-
// If there is an error parsing JSON, print it to the console
44-
println("JSON Error \(err!.localizedDescription)")
45-
}
46-
let results: NSArray = jsonResult["results"] as NSArray
47-
self.delegate.didReceiveAPIResults(jsonResult)
48-
49-
})
50-
51-
task.resume()
52+
get(urlPath)
5253
}
5354
}
5455

56+
func lookupAlbum(collectionId: Int) {
57+
get("https://itunes.apple.com/lookup?id=\(collectionId)&entity=song")
58+
}
59+
5560
}

SwiftTutorial/Album.swift

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,14 +15,16 @@ class Album {
1515
var largeImageURL: String
1616
var itemURL: String
1717
var artistURL: String
18+
var collectionId: Int
1819

19-
init(name: String, price: String, thumbnailImageURL: String, largeImageURL: String, itemURL: String, artistURL: String) {
20+
init(name: String, price: String, thumbnailImageURL: String, largeImageURL: String, itemURL: String, artistURL: String, collectionId: Int) {
2021
self.title = name
2122
self.price = price
2223
self.thumbnailImageURL = thumbnailImageURL
2324
self.largeImageURL = largeImageURL
2425
self.itemURL = itemURL
2526
self.artistURL = artistURL
27+
self.collectionId = collectionId
2628
}
2729

2830
class func albumsWithJSON(allResults: NSArray) -> [Album] {
@@ -64,7 +66,8 @@ class Album {
6466
itemURL = result["trackViewUrl"] as? String
6567
}
6668

67-
var newAlbum = Album(name: name!, price: price!, thumbnailImageURL: thumbnailURL, largeImageURL: imageURL, itemURL: itemURL!, artistURL: artistURL)
69+
var collectionId = result["collectionId"] as? Int
70+
var newAlbum = Album(name: name!, price: price!, thumbnailImageURL: thumbnailURL, largeImageURL: imageURL, itemURL: itemURL!, artistURL: artistURL, collectionId: collectionId!)
6871
albums.append(newAlbum)
6972
}
7073
}

SwiftTutorial/Base.lproj/Main.storyboard

Lines changed: 72 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -78,27 +78,96 @@
7878
<subviews>
7979
<imageView userInteractionEnabled="NO" contentMode="scaleToFill" horizontalHuggingPriority="251" verticalHuggingPriority="251" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="hel-WJ-0Op">
8080
<rect key="frame" x="16" y="89" width="100" height="100"/>
81+
<variation key="widthClass=compact" fixedFrame="YES">
82+
<rect key="frame" x="16" y="72" width="100" height="100"/>
83+
</variation>
8184
</imageView>
85+
<tableView clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="prototypes" style="plain" separatorStyle="default" rowHeight="44" sectionHeaderHeight="22" sectionFooterHeight="22" translatesAutoresizingMaskIntoConstraints="NO" id="3v6-nQ-AZC">
86+
<rect key="frame" x="0.0" y="0.0" width="320" height="568"/>
87+
<color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
88+
<prototypes>
89+
<tableViewCell contentMode="scaleToFill" selectionStyle="blue" hidesAccessoryWhenEditing="NO" indentationLevel="1" indentationWidth="0.0" reuseIdentifier="TrackCell" id="92m-n3-djN" customClass="TrackCell" customModule="SwiftTutorial" customModuleProvider="target">
90+
<autoresizingMask key="autoresizingMask"/>
91+
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="92m-n3-djN" id="x0J-lZ-BOp">
92+
<autoresizingMask key="autoresizingMask"/>
93+
<subviews>
94+
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="▶️" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="gIv-hI-3Cx">
95+
<rect key="frame" x="0.0" y="-21" width="42" height="21"/>
96+
<fontDescription key="fontDescription" type="system" pointSize="17"/>
97+
<color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
98+
<nil key="highlightedColor"/>
99+
<variation key="widthClass=compact" fixedFrame="YES">
100+
<rect key="frame" x="8" y="10" width="23" height="23"/>
101+
</variation>
102+
</label>
103+
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Label" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" minimumScaleFactor="0.5" translatesAutoresizingMaskIntoConstraints="NO" id="sPN-at-1iq">
104+
<rect key="frame" x="0.0" y="-21" width="42" height="21"/>
105+
<fontDescription key="fontDescription" name="HelveticaNeue-Thin" family="Helvetica Neue" pointSize="18"/>
106+
<color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
107+
<nil key="highlightedColor"/>
108+
<variation key="widthClass=compact" fixedFrame="YES">
109+
<rect key="frame" x="39" y="12" width="353" height="21"/>
110+
</variation>
111+
</label>
112+
</subviews>
113+
<variation key="default">
114+
<mask key="subviews">
115+
<exclude reference="gIv-hI-3Cx"/>
116+
<exclude reference="sPN-at-1iq"/>
117+
</mask>
118+
</variation>
119+
<variation key="widthClass=compact">
120+
<mask key="subviews">
121+
<include reference="gIv-hI-3Cx"/>
122+
<include reference="sPN-at-1iq"/>
123+
</mask>
124+
</variation>
125+
</tableViewCellContentView>
126+
<connections>
127+
<outlet property="playIcon" destination="gIv-hI-3Cx" id="LOH-RJ-4RZ"/>
128+
<outlet property="titleLabel" destination="sPN-at-1iq" id="B85-Cf-uLS"/>
129+
</connections>
130+
</tableViewCell>
131+
</prototypes>
132+
<variation key="widthClass=compact" fixedFrame="YES">
133+
<rect key="frame" x="0.0" y="197" width="400" height="403"/>
134+
</variation>
135+
<connections>
136+
<outlet property="dataSource" destination="Nwf-37-TC2" id="vKY-k7-t01"/>
137+
<outlet property="delegate" destination="Nwf-37-TC2" id="gc7-Eb-4Fb"/>
138+
</connections>
139+
</tableView>
82140
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" fixedFrame="YES" text="Title Label" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="7SW-it-u9F">
83-
<rect key="frame" x="149" y="118" width="435" height="42"/>
141+
<rect key="frame" x="149" y="118" width="298" height="42"/>
84142
<fontDescription key="fontDescription" type="system" pointSize="17"/>
85143
<color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
86144
<nil key="highlightedColor"/>
87145
<variation key="widthClass=compact" fixedFrame="YES">
88-
<rect key="frame" x="133" y="118" width="251" height="42"/>
146+
<rect key="frame" x="133" y="101" width="251" height="42"/>
89147
</variation>
90148
</label>
91149
</subviews>
92150
<color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
151+
<variation key="default">
152+
<mask key="subviews">
153+
<exclude reference="3v6-nQ-AZC"/>
154+
</mask>
155+
</variation>
156+
<variation key="widthClass=compact">
157+
<mask key="subviews">
158+
<include reference="3v6-nQ-AZC"/>
159+
</mask>
160+
</variation>
93161
</view>
94162
<connections>
95163
<outlet property="albumCover" destination="hel-WJ-0Op" id="Ans-OY-3NK"/>
96164
<outlet property="titleLabel" destination="7SW-it-u9F" id="rHz-V7-TMF"/>
165+
<outlet property="tracksTableView" destination="3v6-nQ-AZC" id="Tn6-V8-93J"/>
97166
</connections>
98167
</viewController>
99168
<placeholder placeholderIdentifier="IBFirstResponder" id="Jyv-3h-51E" userLabel="First Responder" sceneMemberID="firstResponder"/>
100169
</objects>
101-
<point key="canvasLocation" x="1417.5" y="798"/>
170+
<point key="canvasLocation" x="1416" y="797"/>
102171
</scene>
103172
<!--Navigation Controller-->
104173
<scene sceneID="3tg-ke-aa0">

SwiftTutorial/DetailsViewController.swift

Lines changed: 52 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,17 @@
77
//
88

99
import UIKit
10+
import MediaPlayer
11+
import QuartzCore
1012

11-
class DetailsViewController: UIViewController {
13+
class DetailsViewController: UIViewController, APIControllerProtocol {
1214

1315
var album: Album?
16+
var tracks = [Track]()
17+
lazy var api : APIController = APIController(delegate: self)
18+
var mediaPlayer: MPMoviePlayerController = MPMoviePlayerController()
1419

20+
@IBOutlet weak var tracksTableView: UITableView!
1521
@IBOutlet weak var albumCover: UIImageView!
1622
@IBOutlet weak var titleLabel: UILabel!
1723

@@ -23,6 +29,51 @@ class DetailsViewController: UIViewController {
2329
super.viewDidLoad()
2430
titleLabel.text = self.album?.title
2531
albumCover.image = UIImage(data: NSData(contentsOfURL: NSURL(string: self.album!.largeImageURL)))
32+
33+
// Load in tracks
34+
if self.album != nil {
35+
api.lookupAlbum(self.album!.collectionId)
36+
}
37+
}
38+
39+
// MARK: APIControllerProtocol
40+
func didReceiveAPIResults(results: NSDictionary) {
41+
var resultsArr: NSArray = results["results"] as NSArray
42+
dispatch_async(dispatch_get_main_queue(), {
43+
self.tracks = Track.tracksWithJSON(resultsArr)
44+
self.tracksTableView.reloadData()
45+
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
46+
})
47+
}
48+
49+
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
50+
return tracks.count
51+
}
52+
53+
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
54+
let cell = tableView.dequeueReusableCellWithIdentifier("TrackCell") as TrackCell
55+
let track = tracks[indexPath.row]
56+
cell.titleLabel.text = track.title
57+
cell.playIcon.text = "▶️"
58+
59+
return cell
60+
}
61+
62+
func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
63+
var track = tracks[indexPath.row]
64+
mediaPlayer.stop()
65+
mediaPlayer.contentURL = NSURL(string: track.previewUrl)
66+
mediaPlayer.play()
67+
if let cell = tableView.cellForRowAtIndexPath(indexPath) as? TrackCell {
68+
cell.playIcon.text = "◾️"
69+
}
70+
}
71+
72+
func tableView(tableView: UITableView!, willDisplayCell cell: UITableViewCell!, forRowAtIndexPath indexPath: NSIndexPath!) {
73+
cell.layer.transform = CATransform3DMakeScale(0.1,0.1,1)
74+
UIView.animateWithDuration(0.25, animations: {
75+
cell.layer.transform = CATransform3DMakeScale(1,1,1)
76+
})
2677
}
2778

2879
}

SwiftTutorial/SearchResultsViewController.swift

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
//
88

99
import UIKit
10+
import QuartzCore
1011

1112
class SearchResultsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, APIControllerProtocol {
1213

@@ -102,6 +103,12 @@ class SearchResultsViewController: UIViewController, UITableViewDataSource, UITa
102103
detailsViewController.album = selectedAlbum
103104
}
104105

106+
func tableView(tableView: UITableView!, willDisplayCell cell: UITableViewCell!, forRowAtIndexPath indexPath: NSIndexPath!) {
107+
cell.layer.transform = CATransform3DMakeScale(0.1,0.1,1)
108+
UIView.animateWithDuration(0.25, animations: {
109+
cell.layer.transform = CATransform3DMakeScale(1,1,1)
110+
})
111+
}
105112

106113
}
107114

0 commit comments

Comments
 (0)