0
我有一個程序會記錄當前正在播放的歌曲,但我希望應用程序在後臺運行,所以當用戶在不同的應用程序中或設備被鎖定時,我的應用程序在後臺,到下一首歌,節目就會知道。目前,我可以將當前正在播放的歌曲放到應用程序打開時進行解析。如何讓程序在後臺運行?
func applicationDidEnterBackground(application: UIApplication) {
print("entered background")
NSNotificationCenter.defaultCenter().addObserver(self, selector: "getNowPlayingItem", name: MPMusicPlayerControllerNowPlayingItemDidChangeNotification, object: nil)
musicPlayer.beginGeneratingPlaybackNotifications()
}
func getNowPlayingItem() {
if let nowPlaying = musicPlayer.nowPlayingItem {
let title = nowPlaying[MPMediaItemPropertyTitle] as? String
let artisttest = nowPlaying[MPMediaItemPropertyTitle]
if let artist = nowPlaying[MPMediaItemPropertyArtist] as? String{
let objectPointer = PFObject(className: "Pointer")
let object = PFObject(className: "MasterSongs")
// print("Artist: " + artist)
let query = PFQuery(className: "Pointer")
query.findObjectsInBackgroundWithBlock({
(objects: [AnyObject]?, error: NSError?) -> Void in
var objectIDs = objects as! [PFObject]
for i in 0...objectIDs.count-1{
self.Parsearray.append((objectIDs[i].valueForKey("title") as? String)!)
// print(self.Parsearray)
}
if self.Parsearray.contains(title!){
print("already in db")
}else{
objectPointer["title"] = title
objectPointer["user"] = PFUser.currentUser()
objectPointer["artist"] = artist
objectPointer.saveInBackground()
}
})
}else{
let object = PFObject(className: "MasterSongs")
object.setObject(title!, forKey: "title")
//object.setObject(artist!, forKey: "artist")
object.saveInBackground()
let objectPointer = PFObject(className: "Pointer")
let query = PFQuery(className: "Pointer")
query.findObjectsInBackgroundWithBlock({
(objects: [AnyObject]?, error: NSError?) -> Void in
var objectIDs = objects as! [PFObject]
for i in 0...objectIDs.count-1{
self.Parsearray.append((objectIDs[i].valueForKey("title") as? String)!)
// print(self.Parsearray)
}
if self.Parsearray.contains(title!){
print("already in db")
}else{
objectPointer["title"] = title
objectPointer["user"] = PFUser.currentUser()
objectPointer["artist"] = "No artist found :("
objectPointer.saveInBackground()
}
})
}
}
}
所以我想我知道什麼是錯的,我打電話在視圖中的功能會出現,因爲應用程序將在後臺運行viewWillAppear將不會被調用,除非應用程序打開,你的方法會解決這個問題? – tman0542
只需啓用回答中提到的背景模式,然後測試您的代碼。 – Muneeba
不,它不起作用。我也將它添加到plist http://puu.sh/lGm9b/3459d6f072.png – tman0542