SlideShare una empresa de Scribd logo
1 de 49
Descargar para leer sin conexión
創作 MusicKit
告⽩白情歌
彼得潘
http://apppeterpan.strikingly.com
彼得潘簡介
叫我彼得潘,Peter,Deeplove,
⻤鬼塚,Swift⼩小王⼦子,情歌王⼦子
莫叫我⽼老老師
http://bit.ly/2xe9eOG
MusicKit
付費會員才能開發
實機才能測試
https://developer.apple.com/musickit/
學習重點
• Apple Music API
• StoreKit & MediaPlayer framework
• Apple 官⽅方的 sample code

http://bit.ly/2BfKSVN
Demo App
https://github.com/AppPeterPan/MusicKitDemo
Apple Music API
• Developer Token
• 所有的 API 都需要,⽐比⽅方 search 周杰倫倫的歌
• User Token
• 和使⽤用者有關的 API,⽐比⽅方使⽤用者最近播放的專輯
• 利利⽤用 developer token ⽣生成
⽣生成 MusicKit App 需要的
developer token
http://bit.ly/2DlRLXH
測試 Apple Music API
http://bit.ly/2mUD3j9
測試 Apple Music API
Apple Music API
• API 網⾴頁
• https://apple.co/2vW3MCt
• 以 https://api.music.apple.com/v1/ 開頭
• 存取某個國家的⾳音樂樂樂樂資料料
• https://api.music.apple.com/v1/catalog/{storefront}/albums/{id}
• catalog/{storefront}
• storefront: 國家代碼,ISO-Alpha2 country code
• ex: tw
• http://www.nationsonline.org/oneworld/country_code_list.htm
• 存取個⼈人的⾳音樂樂樂樂資料料
• https://api.music.apple.com/v1/me/ratings/albums/{id}
• me/
從 iTunes 知道
歌⼿手,專輯,歌曲的 id
https://itunes.apple.com/tw/artist/jay-chou/300117743?l=en
https://api.music.apple.com/v1/catalog/tw/artists/300117743
從 iTunes 知道
歌⼿手,專輯,歌曲的 id
https://itunes.apple.com/tw/album/%E5%91%8A%E7%99%BD%E6%B0%A3%E7%90%83/1118757859?i=1118757877&l=en
https://api.music.apple.com/v1/catalog/tw/songs/1118757877
參參數數: include
https://api.music.apple.com/v1/catalog/tw/artists/300117743?include=playlists,music-videos
指定額外包含的 relationship
search
https://api.music.apple.com/v1/catalog/tw/search?types=songs&term=戴佩妮
search
curl -H 'Authorization: Bearer
eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IlFDTjVIWjUzTk4ifQ.
eyJpc3MiOiJHNEhMOThMWDZMIiwiaWF0IjoxNTE2NDUwOTE1LCJleH
AiOjE1MTY0OTQxMTV9.zSdf73HMQcoAgSQqhHEA2xD7b2yz7z-
NsXK4PKsaGdbETsMAylAaMnq2-
GWdDSmKSdSSGZ8HZtnASvAr95ghUA' 'https://api.music.apple.com/
v1/catalog/tw/search?term=戴佩妮' | pbcopy
http://jsoneditoronline.org
search
search
指定 type
curl -H 'Authorization: Bearer
eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IlFDTjVIWjUzTk4ifQ.
eyJpc3MiOiJHNEhMOThMWDZMIiwiaWF0IjoxNTE2NDUwOTE1LCJleH
AiOjE1MTY0OTQxMTV9.zSdf73HMQcoAgSQqhHEA2xD7b2yz7z-
NsXK4PKsaGdbETsMAylAaMnq2-
GWdDSmKSdSSGZ8HZtnASvAr95ghUA' 'https://api.music.apple.com/
v1/catalog/tw/search?types=songs&term=戴佩妮' | pbcopy
http://jsoneditoronline.org
search
分⾴頁
next, limit, offset
limit 的上限 25
curl -H 'Authorization: Bearer
eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IlFDTjVIWjUzTk4ifQ.
eyJpc3MiOiJHNEhMOThMWDZMIiwiaWF0IjoxNTE2NDUwOTE1LCJleH
AiOjE1MTY0OTQxMTV9.zSdf73HMQcoAgSQqhHEA2xD7b2yz7z-
NsXK4PKsaGdbETsMAylAaMnq2-
GWdDSmKSdSSGZ8HZtnASvAr95ghUA' 'https://api.music.apple.com/
v1/catalog/tw/search?types=songs&term=戴佩妮&limit=25' | pbcopy
分⾴頁
curl -H 'Authorization: Bearer
eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IlFDTjVIWjUzTk4ifQ.
eyJpc3MiOiJHNEhMOThMWDZMIiwiaWF0IjoxNTE2NDUwOTE1LCJleH
AiOjE1MTY0OTQxMTV9.zSdf73HMQcoAgSQqhHEA2xD7b2yz7z-
NsXK4PKsaGdbETsMAylAaMnq2-
GWdDSmKSdSSGZ8HZtnASvAr95ghUA' 'https://api.music.apple.com/
v1/catalog/tw/search?types=songs&term=戴佩妮&limit=25&offset=25' |
pbcopy
⽅方法1: 從 next 得到下⼀一⾴頁的網址
⽅方法2: ⾃自⼰己累加 offset
沒有下⼀一⾴頁: 沒有 next 欄欄位
iOS App 範例例程式
模仿 Apple Sample Code
App 要求存取 music
的權限
閃退
2018-01-20 23:34:54.867234+0800 MusicKitDemo[8440:3181243] [access] This app
has crashed because it attempted to access privacy-sensitive data without a usage
description. The app's Info.plist must contain an NSAppleMusicUsageDescription key
with a string value explaining to the user how the app uses this data.
SKCloudServiceController.requestAuthorization(_:)
抓取 Apple Music 的⾳音樂樂樂樂不不需要使⽤用者同意
但是播放⾳音樂樂樂樂需要
要求存取 Apple Music的權限
Privacy - Media Library Usage Description
要求存取 Apple Music的權限
權限取得步驟
• 取得 developer token
• StoreKit & SKCloudServiceController
• 徵求使⽤用者同意
SKCloudServiceController.requestAuthorization(_:)
• 如果 authorized,取得 Cloud Service Capabilities
權限取得步驟
• 如果能⼒力力包含 playback,表示使⽤用者有付⽉月租,可
以聽歌
• 取得 user token & store 的國家代碼
• 如果不不能 playback, 但可以訂閱,
(musicCatalogSubscriptionEligible),顯示要使⽤用者
訂閱的畫⾯面
• SKCloudServiceSetupViewController
SKCloudServiceSetupViewController
打開 iCloud ⾳音樂樂樂樂資料料庫的開關
才能將⾳音樂樂樂樂加到播放列列表
其它程式解說
Search 和分⾴頁
• SearchTableViewController &
RecentTableViewController 繼承
MediaItemTableViewController
• performAppleMusicCatalogSearch
• 利利⽤用 nextPath 參參數數組合下⼀一⾴頁的 URL
https://apple.co/2DrAfFs
解析 JSON
• processMediaItems
• JSONKeys.swift
• MediaItem.swift
沒有更更多資料料了了
• 沒有 next 欄欄位
• search 告⽩白氣球 demo
func processMediaItems(from json: Data) throws -> ([MediaItem], String?) {
guard let jsonDictionary = try JSONSerialization.jsonObject(with:
json, options: []) as? [String: Any],
let results = jsonDictionary[ResponseRootJSONKeys.results] as?
[String: [String: Any]] else {
throw
SerializationError.missing(ResponseRootJSONKeys.results)
}
var songMediaItems = [MediaItem]()
var next: String?
if let songsDictionary = results[ResourceTypeJSONKeys.songs] {
next = songsDictionary[ResponseRootJSONKeys.next] as? String
search hint
https://apple.co/2mUHYRf
search hint
curl -H 'Authorization: Bearer
eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IjVaOVgz
SFgyUkMifQ.eyJpc3MiOiJHNEhMOThMWDZMIiwiaWF0Ijox
NTE1OTI1MTYzLCJleHAiOjE1MzE2NDk5NjN9.7SCwUodMxi
p2NYOdkNy40vvj9YTRzHeyUcmLIovXV1jfDQbu9guzFLDqk
0dzNaXti_VrXYH8UbzxQbv8LqZr2Q' "https://
api.music.apple.com/v1/catalog/tw/search/hints?term=戴" |
pbcopy
最近播放的專輯
https://apple.co/2DwHOKQ
需要 user token
MediaPlayer
播放⾳音樂樂樂樂
• MediaPlayer framework
• MPMusicPlayerController
• function play
正在播放的⾳音樂樂樂樂
• nowPlayingItem
• playbackStoreID
• 從 ID 找 song 的資訊
https://apple.co/2FYx3yC
使⽤用者的 playlist
func getPlaylists() -> [MPMediaPlaylist] {
let playlistsQuery = MPMediaQuery.playlists()
if let playlists = playlistsQuery.collections as? [MPMediaPlaylist] {
return playlists
} else {
return [MPMediaPlaylist]()
}
}
add to playlist
func addItem(withProductID productID: String, completionHandler: ((Error?) ->
Swift.Void)? = nil)
Rating
like / dislike
https://apple.co/2Dn5QEf
one more thing
JSONDecoder 解析 JSON
http://bit.ly/2DpQnmR
JSONDecoder 解析 JSON
import PlaygroundSupport
import Foundation
PlaygroundPage.current.needsIndefiniteExecution = true
struct SearchResults: Codable {
struct Attribute: Codable {
var name: String
var artistName: String
var albumName: String
}
struct SongData: Codable {
var id: String
var attributes: Attribute
}
struct Songs: Codable {
var href: URL
var next: URL?
var data: [SongData]
}
struct Results: Codable {
var songs: Songs
}
var results: Results
}
JSONDecoder 解析 JSON
let appleMusicAPIBaseURLString = "api.music.apple.com"
let countryCode = "tw"
let developerToken =
"eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IlFDTjVIWjUzTk4ifQ.eyJpc3MiOiJHNEhMOThMWDZMIiwiaWF0IjoxNTE2NTAyMzU1LCJle
HAiOjE1MTY1NDU1NTV9.2d1W7lqX2g2AG3Pzbe-UJ6-yoCXhaAxsqssEE98hIipdB7BORIJUpzE9mKMmrwv5ibAq0HCnStfOzckhFMUXBw"
var urlComponents = URLComponents()
urlComponents.scheme = "https"
urlComponents.host = appleMusicAPIBaseURLString
urlComponents.path = "/v1/catalog/(countryCode)/search"
let urlParameters = ["term": "周杰倫倫", "types": "songs"]
var queryItems = [URLQueryItem]()
for (key, value) in urlParameters {
queryItems.append(URLQueryItem(name: key, value: value))
}
urlComponents.queryItems = queryItems
var urlRequest = URLRequest(url: urlComponents.url!)
urlRequest.httpMethod = "GET"
urlRequest.addValue("Bearer (developerToken)", forHTTPHeaderField: "Authorization")
let task = URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
guard error == nil, let urlResponse = response as? HTTPURLResponse, urlResponse.statusCode == 200, let data =
data else {
print("task error")
return
}
let decoder = JSONDecoder()
if let songResults = try? decoder.decode(SearchResults.self, from: data) {
for song in songResults.results.songs.data {
print(song.attributes.name)
}
} else {
print("JSON error")
}
}
task.resume()

Más contenido relacionado

Similar a 創作 MusicKit 告白情歌

Chat bot making process using Python 3 & TensorFlow
Chat bot making process using Python 3 & TensorFlowChat bot making process using Python 3 & TensorFlow
Chat bot making process using Python 3 & TensorFlow
Jeongkyu Shin
 
Wp dev day_using_the_nokia_music_apis
Wp dev day_using_the_nokia_music_apisWp dev day_using_the_nokia_music_apis
Wp dev day_using_the_nokia_music_apis
Steve Robbins
 
Open source software for startups
Open source software for startupsOpen source software for startups
Open source software for startups
victorneo
 

Similar a 創作 MusicKit 告白情歌 (20)

Introduction to Social APIs
Introduction to Social APIsIntroduction to Social APIs
Introduction to Social APIs
 
Application Programming Interfaces
Application Programming InterfacesApplication Programming Interfaces
Application Programming Interfaces
 
Jeff Siarto: Party Like It’s 1984, An introduction to social APIs
Jeff Siarto: Party Like It’s 1984, An introduction to social APIsJeff Siarto: Party Like It’s 1984, An introduction to social APIs
Jeff Siarto: Party Like It’s 1984, An introduction to social APIs
 
.NET Fest 2018. Антон Молдован. One year of using F# in production at SBTech
.NET Fest 2018. Антон Молдован. One year of using F# in production at SBTech.NET Fest 2018. Антон Молдован. One year of using F# in production at SBTech
.NET Fest 2018. Антон Молдован. One year of using F# in production at SBTech
 
Motion Django Meetup
Motion Django MeetupMotion Django Meetup
Motion Django Meetup
 
iOSDevCamp 2011 - Getting "Test"-y: Test Driven Development & Automated Deplo...
iOSDevCamp 2011 - Getting "Test"-y: Test Driven Development & Automated Deplo...iOSDevCamp 2011 - Getting "Test"-y: Test Driven Development & Automated Deplo...
iOSDevCamp 2011 - Getting "Test"-y: Test Driven Development & Automated Deplo...
 
Goodle Developer Days London 2008 - Open Social Update
Goodle Developer Days London 2008 - Open Social UpdateGoodle Developer Days London 2008 - Open Social Update
Goodle Developer Days London 2008 - Open Social Update
 
Yahoo is open to developers
Yahoo is open to developersYahoo is open to developers
Yahoo is open to developers
 
Lessons Learned - Building YDN
Lessons Learned - Building YDNLessons Learned - Building YDN
Lessons Learned - Building YDN
 
分享無名小站 API
分享無名小站 API分享無名小站 API
分享無名小站 API
 
Chat bot making process using Python 3 & TensorFlow
Chat bot making process using Python 3 & TensorFlowChat bot making process using Python 3 & TensorFlow
Chat bot making process using Python 3 & TensorFlow
 
Goodle Developer Days Munich 2008 - Open Social Update
Goodle Developer Days Munich 2008 - Open Social UpdateGoodle Developer Days Munich 2008 - Open Social Update
Goodle Developer Days Munich 2008 - Open Social Update
 
Wp dev day_using_the_nokia_music_apis
Wp dev day_using_the_nokia_music_apisWp dev day_using_the_nokia_music_apis
Wp dev day_using_the_nokia_music_apis
 
MySpace Open Platform enhancements with OpenSocial 0.9
MySpace Open Platform enhancements with OpenSocial 0.9MySpace Open Platform enhancements with OpenSocial 0.9
MySpace Open Platform enhancements with OpenSocial 0.9
 
Mashup University 4: Intro To Mashups
Mashup University 4: Intro To MashupsMashup University 4: Intro To Mashups
Mashup University 4: Intro To Mashups
 
Adopting F# at SBTech
Adopting F# at SBTechAdopting F# at SBTech
Adopting F# at SBTech
 
The Face Behind Facebook
The Face Behind FacebookThe Face Behind Facebook
The Face Behind Facebook
 
Java 8, Streams & Collectors, patterns, performances and parallelization
Java 8, Streams & Collectors, patterns, performances and parallelizationJava 8, Streams & Collectors, patterns, performances and parallelization
Java 8, Streams & Collectors, patterns, performances and parallelization
 
"Managing API Complexity". Matthew Flaming, Temboo
"Managing API Complexity". Matthew Flaming, Temboo"Managing API Complexity". Matthew Flaming, Temboo
"Managing API Complexity". Matthew Flaming, Temboo
 
Open source software for startups
Open source software for startupsOpen source software for startups
Open source software for startups
 

Más de 彼得潘 Pan

Standford 2015 week8
Standford 2015 week8Standford 2015 week8
Standford 2015 week8
彼得潘 Pan
 

Más de 彼得潘 Pan (20)

如何變成 iOS App 開發魔法師 (1 小時)
如何變成 iOS App 開發魔法師 (1 小時)如何變成 iOS App 開發魔法師 (1 小時)
如何變成 iOS App 開發魔法師 (1 小時)
 
如何變成 iOS App 開發魔法師
如何變成 iOS App 開發魔法師如何變成 iOS App 開發魔法師
如何變成 iOS App 開發魔法師
 
Xcode 的 git 版本管理
Xcode 的 git 版本管理Xcode 的 git 版本管理
Xcode 的 git 版本管理
 
消滅永生不死吸血鬼物件的 ARC
消滅永生不死吸血鬼物件的 ARC消滅永生不死吸血鬼物件的 ARC
消滅永生不死吸血鬼物件的 ARC
 
利用 iOS App 技術創業的 13 個方法
利用 iOS App 技術創業的 13 個方法利用 iOS App 技術創業的 13 個方法
利用 iOS App 技術創業的 13 個方法
 
不能承受的感動 - iOS App實機測試
不能承受的感動 - iOS App實機測試不能承受的感動 - iOS App實機測試
不能承受的感動 - iOS App實機測試
 
如何變成iOS App開發魔法師
如何變成iOS App開發魔法師如何變成iOS App開發魔法師
如何變成iOS App開發魔法師
 
第一次程式親密接觸
第一次程式親密接觸第一次程式親密接觸
第一次程式親密接觸
 
打造你的第一個iPhone APP
打造你的第一個iPhone APP打造你的第一個iPhone APP
打造你的第一個iPhone APP
 
你的程式開發初體驗 (以Swift為例)
你的程式開發初體驗 (以Swift為例)你的程式開發初體驗 (以Swift為例)
你的程式開發初體驗 (以Swift為例)
 
Standford 2015 week9
Standford 2015 week9Standford 2015 week9
Standford 2015 week9
 
Standford 2015 week8
Standford 2015 week8Standford 2015 week8
Standford 2015 week8
 
Standford 2015 week7: 1. Unwind Segues, Alerts, Timers, View Animation 2. Dyn...
Standford 2015 week7: 1. Unwind Segues, Alerts, Timers, View Animation 2. Dyn...Standford 2015 week7: 1. Unwind Segues, Alerts, Timers, View Animation 2. Dyn...
Standford 2015 week7: 1. Unwind Segues, Alerts, Timers, View Animation 2. Dyn...
 
Standford 2015 week6
Standford 2015 week6Standford 2015 week6
Standford 2015 week6
 
Standford 2015 week5: 1.View Controller Lifecycle, Autolayout 2. Scroll View ...
Standford 2015 week5: 1.View Controller Lifecycle, Autolayout 2. Scroll View ...Standford 2015 week5: 1.View Controller Lifecycle, Autolayout 2. Scroll View ...
Standford 2015 week5: 1.View Controller Lifecycle, Autolayout 2. Scroll View ...
 
Standford 2015 week4: 1.Protocols and Delegation, Gestures 2. Multiple MVCs
Standford 2015 week4: 1.Protocols and Delegation, Gestures 2. Multiple MVCsStandford 2015 week4: 1.Protocols and Delegation, Gestures 2. Multiple MVCs
Standford 2015 week4: 1.Protocols and Delegation, Gestures 2. Multiple MVCs
 
Standford 2015 week3: Objective-C Compatibility, Property List, Views
Standford 2015 week3: Objective-C Compatibility, Property List, ViewsStandford 2015 week3: Objective-C Compatibility, Property List, Views
Standford 2015 week3: Objective-C Compatibility, Property List, Views
 
Standford 2015 iOS讀書會 week2: 1. Applying MVC 2. More Swift and Foundation Fra...
Standford 2015 iOS讀書會 week2: 1. Applying MVC 2. More Swift and Foundation Fra...Standford 2015 iOS讀書會 week2: 1. Applying MVC 2. More Swift and Foundation Fra...
Standford 2015 iOS讀書會 week2: 1. Applying MVC 2. More Swift and Foundation Fra...
 
Standford 2015 iOS讀書會 week1: 1.Logistics , iOS 8 Overview 2. More Xcode and S...
Standford 2015 iOS讀書會 week1: 1.Logistics , iOS 8 Overview 2. More Xcode and S...Standford 2015 iOS讀書會 week1: 1.Logistics , iOS 8 Overview 2. More Xcode and S...
Standford 2015 iOS讀書會 week1: 1.Logistics , iOS 8 Overview 2. More Xcode and S...
 
打造你的第一個 iOS App
打造你的第一個 iOS App  打造你的第一個 iOS App
打造你的第一個 iOS App
 

創作 MusicKit 告白情歌