This repository was archived by the owner on Jun 19, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSecondViewController.swift
More file actions
310 lines (252 loc) · 10.8 KB
/
SecondViewController.swift
File metadata and controls
310 lines (252 loc) · 10.8 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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
//
// SecondViewController.swift
// Song Finder
//
// Created by Arjun Tambe on 7/11/16.
// Copyright © 2016 Arjun Tambe. All rights reserved.
//
/* FEATURES TO INTEGRATE:
-save and display search history; allow search history elements to be clicked to automatically search, like spotify
-now playing display bar somewhere, and allow user to see more info including cover art
-forward and backward feature, and a play queue [need to discuss how queue will work]
-allow play/pause control from the control panel
-display play time in the control panel
-soundcloud uses the web app, instead of the ios app. won't allow saved music to play from it
-add youtube
*/
import Foundation
import MediaPlayer
import UIKit
class SecondViewController: UIViewController, UISearchBarDelegate, UITableViewDelegate, UITableViewDataSource {
var resultsArray = [SongData]()
var trackManager = TrackManager()
@IBOutlet var searchBar: UISearchBar!
@IBOutlet weak var resultsTable: UITableView!
@IBOutlet var playPauseButton: UIButton!
let tapRecognizer = UITapGestureRecognizer()
var spotifyResults: [AnyObject!] = []
var appleMusicResults: [AnyObject!] = []
var soundCloudResults: [AnyObject!] = []
var localResults: [AnyObject!] = []
var findResultsGroup = dispatch_group_create()
override func viewDidLoad() {
if (loggedInSpotify) {
completeSpotifyLogin()
}
searchBar.delegate = self
resultsTable.dataSource = self
resultsTable.delegate = self
let selector = #selector(self.handleTap(_:))
let tapGesture = UITapGestureRecognizer(target: self, action: selector)
tapGesture.cancelsTouchesInView = false
tapGesture.numberOfTapsRequired = 1
view.addGestureRecognizer(tapGesture)
}
func handleTap(sender: UITapGestureRecognizer) {
self.searchBar.endEditing(true)
}
func completeSpotifyLogin() {
if (spotifyPlayer == nil) {
spotifyPlayer = SPTAudioStreamingController(clientId: spotifyID)
}
spotifyPlayer!.loginWithSession(SPTAuth.defaultInstance().session, callback: { (error) in
if error != nil {
print ("error logging in: \(error)")
return;
}
})
}
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
//clear results
}
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
let query = searchBar.text
if (loggedInSpotify) {
searchSpotify(query!)
}
if (loggedInAppleMusic) {
searchAppleMusic(query!)
}
if (loggedInSoundCloud) {
searchSoundCloud(query!)
}
searchLocalMusic(query!)
self.searchBar.endEditing(true)
dispatch_group_notify(findResultsGroup, dispatch_get_main_queue()) {
if (loggedInSpotify) {
self.convertSongData(&self.spotifyResults, platform: Platform.spotify)
}
if (loggedInAppleMusic) {
self.convertSongData(&self.appleMusicResults, platform: Platform.appleMusic)
}
if (loggedInSoundCloud) {
self.convertSongData(&self.soundCloudResults, platform: Platform.soundCloud)
}
self.convertSongData(&self.localResults, platform: Platform.local)
self.resultsArray = self.compileResults()
self.resultsTable.reloadData()
}
}
func convertSongData(inout resultArray: [AnyObject!], platform: Platform) {
var newArray = [SongData]()
for i in 0..<resultArray.count {
let song = SongData(song: resultArray[i], songPlatform: platform)
newArray.append(song)
print(song.getName())
}
resultArray = newArray
}
func compileResults() -> [SongData] {
var returnArray = [SongData]()
for i in 0..<2 {
if (loggedInSpotify) {
if (spotifyResults.count > i) {
returnArray.append((spotifyResults[i] as! SongData))
}
}
if (loggedInAppleMusic) {
if (appleMusicResults.count > i) {
returnArray.append((appleMusicResults[i] as! SongData))
}
}
if (loggedInSoundCloud) {
if (soundCloudResults.count > i) {
returnArray.append((soundCloudResults[i] as! SongData))
}
}
if (localResults.count > i) {
returnArray.append(localResults[i] as! SongData)
}
}
return returnArray
}
func searchAppleMusic(input: String) {
dispatch_group_enter(self.findResultsGroup)
let queryURL = convertToHTML(input)
let url = NSURL(string: queryURL)!
let request: NSURLRequest = NSURLRequest(URL: url)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
print (error)
return
}
do {
let resultJSON = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
if resultJSON.count>0 && resultJSON["results"]!.count>0 {
if (self.appleMusicResults.count > 0) {
self.appleMusicResults.removeAll()
}
self.appleMusicResults = resultJSON["results"] as! [Dictionary<String, AnyObject>]
dispatch_group_leave(self.findResultsGroup)
}
} catch {
print ("error")
}
}
task.resume()
}
//converts string to HTML for searchAppleMusic
private func convertToHTML(input: String) -> String{
let itunesSearchTerm = input.stringByReplacingOccurrencesOfString(" ", withString: "+", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil)
let result = itunesSearchTerm.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
return("https://itunes.apple.com/search?term=\(result)&media=music&entity=song&attribute=songTerm")
}
//Searches spotify based on an input string
func searchSpotify(searchTerm: String) {
dispatch_group_enter(findResultsGroup)
SPTSearch.performSearchWithQuery(searchTerm, queryType: SPTSearchQueryType.QueryTypeTrack, accessToken: SPTAuth.defaultInstance().session.accessToken) { (error, searchResult) in
if (error != nil) {
print("error: \(error)")
} else {
if (self.spotifyResults.count > 0) {
self.spotifyResults.removeAll()
}
if ((searchResult as! SPTListPage).totalListLength > 0) {
self.spotifyResults = (searchResult as! SPTListPage).items
} else {
//need some handling if no results
}
dispatch_group_leave(self.findResultsGroup)
}
}
}
func searchSoundCloud(input: String) {
let queryHTMLForm = input.stringByReplacingOccurrencesOfString(" ", withString: "%20")
let startOfURL =
"https://api.soundcloud.com/tracks.json?oauth_token=" + scToken! + "&client_id=" + soundcloudID + "&q="
let url = NSURL(string: startOfURL + queryHTMLForm)
dispatch_group_enter(findResultsGroup)
var jsonString = ""
do {
jsonString = try String(contentsOfURL: url!, encoding: NSUTF8StringEncoding)
} catch {
print (error)
}
let data: NSData = jsonString.dataUsingEncoding(NSUTF8StringEncoding)!
do {
if (soundCloudResults.count > 0) {
soundCloudResults.removeAll()
}
soundCloudResults = try (NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0)) as! NSArray) as! [Dictionary<String, AnyObject>]
dispatch_group_leave(findResultsGroup)
} catch {
print (error)
}
}
func searchLocalMusic(searchTerm: String) {
dispatch_group_enter(findResultsGroup)
let query = MPMediaQuery.songsQuery()
let predicate = MPMediaPropertyPredicate(value: searchTerm, forProperty: MPMediaItemPropertyTitle, comparisonType: MPMediaPredicateComparison.Contains)
query.addFilterPredicate(predicate)
if (localResults.count > 0) {
localResults.removeAll()
}
localResults = query.items!
dispatch_group_leave(findResultsGroup)
}
func numberOfSectionsInTableview(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView:UITableView, numberOfRowsInSection section:Int) -> Int
{
return resultsArray.count
}
func tableView(tableView: UITableView,
cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell = UITableViewCell(style:UITableViewCellStyle.Default, reuseIdentifier:"cell0")
cell.textLabel?.text = "\(resultsArray[indexPath.row].getName()) ( \(resultsArray[indexPath.row].getPlatform())"
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let selectedSong = resultsArray[indexPath.row]
trackManager.beginPlaying(selectedSong)
playPauseButton.setBackgroundImage(UIImage(named: "pause.png"), forState: UIControlState.Normal)
}
@IBAction func playPauseButtonPressed(sender: AnyObject!) {
if(trackManager.playing()) {
pause()
} else {
resume()
}
}
override func remoteControlReceivedWithEvent(event: UIEvent?) {
let type = event!.subtype
if (type == UIEventSubtype.RemoteControlPlay) {
resume()
} else if (type == UIEventSubtype.RemoteControlPause) {
pause()
} else if (type == UIEventSubtype.RemoteControlNextTrack) {
//handle next track command
} else if (type == UIEventSubtype.RemoteControlPreviousTrack) {
//handle previous track command
} }
private func pause() {
trackManager.pause()
playPauseButton.setBackgroundImage(UIImage(named: "play.jpg"), forState: UIControlState.Normal)
}
private func resume() {
trackManager.resume()
playPauseButton.setBackgroundImage(UIImage(named: "pause.png"), forState: UIControlState.Normal)
}
}