Building Spotify App in Swift 5 & UIKit - Part 22 - Create Playlist (Xcode 12, 2021, Swift 5)
LibraryPlaylistsViewController
: 스포티파이 API 호출을 통해 현재 유저의 플레이리스트 정보 리턴noPlaylistsView
/ 플레이리스트 목록 테이블 뷰 보여주기LibraryViewController
: 우측 네비게이션 아이템 생성 기능 추가 private func fetchData() {
APICaller.shared.getCurrentUserPlaylists { [weak self] result in
guard let self = self else { return }
switch result {
case .success(let playlists):
self.playlists = playlists
DispatchQueue.main.async {
self.updateUI()
}
case .failure(let error):
print(error.localizedDescription)
}
}
}
private func updateUI() {
if playlists.isEmpty {
noPlaylistsView.isHidden = false
tableView.isHidden = true
} else {
tableView.reloadData()
noPlaylistsView.isHidden = true
tableView.isHidden = false
}
}
noPlaylistsView
또는 tableView
를 보여줄지 결정isHidden
을 통해 조정func showCreatePlaylistAlert() {
let alert = UIAlertController(title: "New Playlists", message: "Enter Playlist's Name", preferredStyle: .alert)
alert.addTextField { textField in
textField.placeholder = "Playlist..."
}
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
alert.addAction(UIAlertAction(title: "Create", style: .default, handler: { _ in
guard
let field = alert.textFields?.first,
let text = field.text,
!text.trimmingCharacters(in: .whitespaces).isEmpty else {
return
}
APICaller.shared.createPlaylist(with: text) { [weak self] success in
guard let self = self else { return }
if success {
self.fetchData()
print("Successfully created")
} else {
print("Failed to create playlists")
}
}
}))
present(alert, animated: true)
}
public func createPlaylist(with name: String, completionHandler: @escaping (Bool)->()) {
getCurrentUserProfile { [weak self] result in
guard let self = self else { return }
switch result {
case .success(let profile):
let urlString = Constants.baseAPIURL + "/users/\(profile.id)/playlists"
self.createRequest(with: URL(string: urlString), type: .POST) { request in
var request = request
let json = ["name" : name]
request.httpBody = try? JSONSerialization.data(withJSONObject: json, options: .fragmentsAllowed)
URLSession.shared.dataTask(with: request) { data, response, error in
guard
let data = data,
error == nil else {
completionHandler(false)
return
}
do {
let result = try JSONSerialization.jsonObject(with: data, options: .fragmentsAllowed)
if let response = result as? [String:Any], response["id"] as? String != nil {
print(response)
completionHandler(true)
} else {
print("FAILED TO GET ID")
completionHandler(false)
}
} catch {
print(error.localizedDescription)
completionHandler(false)
}
}
.resume()
}
case .failure(let error):
print(error.localizedDescription)
break
}
}
}
getCurrentUserProfile
함수를 통해 현재 유저 프로필 정보 리턴 → 해당 유저의 플레이리스트를 생성하는 URLRequest 구현 private func updateBarButton() {
switch toggleView.state {
case .playlist:
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(didTapAdd))
case .album:
navigationItem.rightBarButtonItem = nil
}
}
@objc private func didTapAdd() {
playlistVC.showCreatePlaylistAlert()
}
LibraryViewController
단에서 LibraryPlaylistsViewController
의 함수를 사용 가능하도록 하는 네비게이션 바 버튼 아이템updateBarButton()
함수는 스크롤이 변경될 때마다 호출