AGGIORNAMENTO IOS 11.2 con Swift 4:
Ora, se si utilizza AVPlayer per riprodurre la musica i file dovresti anche configurare MPNowPlayingInfoCenter.default()
per mostrare ora le informazioni di gioco sulla schermata di blocco.
Il codice di seguito mostrerà ora i controlli di riproduzione sullo schermo ma non sarà in grado di rispondere a nessun comando.
Se anche voi volete controlli a lavorare si dovrebbe verificare progetto di esempio di Apple qui: https://developer.apple.com/library/content/samplecode/MPRemoteCommandSample/Introduction/Intro.html#//apple_ref/doc/uid/TP40017322
codice di esempio di Apple copre tutto ma trovo confuso.
Se si desidera riprodurre il suono e mostrare i controlli sulla schermata di blocco, questi passaggi andranno bene.
NOTA IMPORTANTE: Se siete NON utilizzando AVPlayer per riprodurre l'audio. Se si utilizzano librerie di terze parti per generare suoni o riprodurre un file audio, è necessario leggere i commenti all'interno del codice. Inoltre, se si utilizza il simulatore di ios 11.2, non sarà possibile visualizzare alcun controllo sulla schermata di blocco. Dovresti usare un dispositivo per vederlo funzionare.
1- Seleziona progetto -> -> capabilites impostare le modalità background su -> tick Audio, AirPlay e Picture in Picture

2- AppDelegate.swift del file dovrebbe essere simile questo:
import UIKit
import AVFoundation
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate
{
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool
{
// Override point for customization after application launch.
do
{
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
//!! IMPORTANT !!
/*
If you're using 3rd party libraries to play sound or generate sound you should
set sample rate manually here.
Otherwise you wont be able to hear any sound when you lock screen
*/
//try AVAudioSession.sharedInstance().setPreferredSampleRate(4096)
}
catch
{
print(error)
}
// This will enable to show nowplaying controls on lock screen
application.beginReceivingRemoteControlEvents()
return true
}
}
3- ViewController.swift dovrebbe assomigliare a questo:
import UIKit
import AVFoundation
import MediaPlayer
class ViewController: UIViewController
{
var player : AVPlayer = AVPlayer()
override func viewDidLoad()
{
super.viewDidLoad()
let path = Bundle.main.path(forResource: "music", ofType: "mp3")
let url = URL(fileURLWithPath: path!)
// !! IMPORTANT !!
/*
If you are using 3rd party libraries to play sound
or generate sound you should always setNowPlayingInfo
before you create your player object.
right:
self.setNowPlayingInfo()
let notAVPlayer = SomePlayer()
wrong(You won't be able to see any controls on lock screen.):
let notAVPlayer = SomePlayer()
self.setNowPlayingInfo()
*/
self.setNowPlayingInfo()
self.player = AVPlayer(url: url)
}
func setNowPlayingInfo()
{
let nowPlayingInfoCenter = MPNowPlayingInfoCenter.default()
var nowPlayingInfo = nowPlayingInfoCenter.nowPlayingInfo ?? [String: Any]()
let title = "title"
let album = "album"
let artworkData = Data()
let image = UIImage(data: artworkData) ?? UIImage()
let artwork = MPMediaItemArtwork(boundsSize: image.size, requestHandler: { (_) -> UIImage in
return image
})
nowPlayingInfo[MPMediaItemPropertyTitle] = title
nowPlayingInfo[MPMediaItemPropertyAlbumTitle] = album
nowPlayingInfo[MPMediaItemPropertyArtwork] = artwork
nowPlayingInfoCenter.nowPlayingInfo = nowPlayingInfo
}
@IBAction func startPlayingButtonPressed(_ sender: Any)
{
self.player.play()
}
RISPOSTA VECCHIO IOS 8.2:
risposta di Patrick è totalmente ragione.
Ma sarò scrivere quello che faccio per ios 8.2:
aggiungo Info.plist modalità di sfondo richieste di mia app come qui di seguito:

e nel mio AppDelegate.h aggiungere queste importazioni:
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>
Poi nel mio AppDelegate.m ho scritto didFinishLaunchingWithOptionsthis applicazione esattamente come di seguito:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
return YES;
}
Ora App mantiene la riproduzione di musica, anche se lo schermo è bloccato :)
vedere la mia risposta in questo Que, troverete la vostra soluzione [Clicca qui per vedere la risposta] [1 ] [1]: http: // stackoverflow.it/questions/15470452/is-it-possible-to-play-video-using-avplayer-in-background –