Reputation: 5936
Im getting an error
No visible @interfcae GlobalMediaPlayer declares selector add sublayer
.h
#import <Foundation/Foundation.h>
#import <AVFoundation/AVFoundation.h>
@interface GlobalMediaPlayer : NSObject
+(GlobalMediaPlayer *)sharedInstance;
-(void)playFromURL:(NSString *)url;
.m
#import "GlobalMediaPlayer.h"
static GlobalMediaPlayer *sharedInstance = nil;
@interface GlobalMediaPlayer ()
{
AVPlayer *avPlayer;
}
@end
@implementation GlobalMediaPlayer
-(id)init{
if(self = [super init]){
}
return self;
}
+(GlobalMediaPlayer *)sharedInstance{
if(!sharedInstance){
sharedInstance = [[[self class] alloc] init];
}
return sharedInstance;
}
-(void)playFromURL:(NSString *)url{
avPlayer = [AVPlayer playerWithURL:[NSURL URLWithString:@"http://www.someurl/something.mp3"]];
AVPlayerLayer *avPlayerLayer = [AVPlayerLayer playerLayerWithPlayer:avPlayer];
avPlayerLayer.frame = CGRectMake(0, 0, 1920, 1020);
//[self addSublayer:avPlayerLayer]; <---- No visible @interfcae GlobalMediaPlayer declares selector add sublayer error
[avPlayer play];
}
using it
[[GlobalMediaPlayer sharedInstance] playFromURL:resourceUrl];
Upvotes: 1
Views: 295
Reputation: 4558
There's no real advantage to wrapping AVPlayer
code in a singleton, as the player needs to be able to render its video in a CALayer
so it's typically best to have the player code in the UIViewController
that is going to be presenting the content.
So in your view controller:
@interface MyViewController: UIViewController
@property (nonatomic, strong) AVPlayer *player;
@property (nonatomic, weak) AVPlayerLayer *playerLayer;
@end
- (void)playFromURL:(NSString *)url {
//Instantiate the player and player layer
AVPlayer *player = [AVPlayer playerWithURL:url];
AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:player];
//Add the player layer as a sublayer of the desired view or subview
playerLayer.frame = self.view.frame;
[self.view.layer addSublayer:playerLayer];
[player play];
//Retain a reference to the player and player layer for controls/removal
self.avPlayer = player;
self.playerLayer = playerLayer;
}
Edit I notice from your sample code that the URL points to an MP3. In that case you don't need to worry about creating an AVPlayerLayer
at all. Simply instantiating the player and calling play
is enough.
Upvotes: 1