How do I play a video on tvOS for Apple TV? - xcode

I started a blank tvOS project and created the following code:
- (void)viewDidLoad
{
[super viewDidLoad];
AVPlayer *avPlayer = [AVPlayer playerWithURL:[NSURL URLWithString:#"http://www.myurl.com/myvideo.mp4"]];
AVPlayerLayer *avPlayerLayer = [AVPlayerLayer playerLayerWithPlayer:avPlayer];
avPlayerLayer.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
[self.view.layer addSublayer:avPlayerLayer];
[avPlayer play];
}
Nothing happens in the simulator though once the app loads. No video, nothing, just a blank translucent screen in my Apple TV simulator.
What's the proper way to play a sample video on app launch for an Apple TV app from an HTTP source?

I just pasted your code in my tvOS sample project, replaced the URL and ran it.
Nothing happened. Well, except for the fact that there's a log entry telling me that App Transport Security has blocked my URL request.
So I headed to the Info.plist, disabled ATS and upon next launch the video showed up just fine.
So if you're also using a non-HTTPS URL you're very likely running into this issue which is easily fixed by either using an HTTPS URL, disabling ATS completely or allowing specific non-HTTPs URLs in your Info.plist.
P.S.: I used this video for testing.

You could also use TVML and TVMLJS
https://developer.apple.com/library/prerelease/tvos/documentation/TVMLJS/Reference/TVJSFrameworkReference/
Adhere to the 'TVApplicationControllerDelegate' protocol and add some properties.
AppDelegate.h
#interface AppDelegate : UIResponder <UIApplicationDelegate, TVApplicationControllerDelegate>
...
#property (strong, nonatomic) TVApplicationController *appController;
#property (strong, nonatomic) TVApplicationControllerContext *appControllerContext;
Then add the following to 'didFinishLaunchingWithOptions'
AppDelegate.m
#define url #"http://localhost:8000/main.js"
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.appControllerContext = [[TVApplicationControllerContext alloc] init];
NSURL *javascriptURL = [NSURL URLWithString:url];
self.appControllerContext.javaScriptApplicationURL= javascriptURL;
for (id key in launchOptions) {
id val=[launchOptions objectForKey:key];
NSLog(#"key=%# value=%#", key, val);
if([val isKindOfClass:[NSString class]]) [self.appControllerContext.launchOptions objectForKey:val];
self.appController = [[TVApplicationController alloc] initWithContext:self.appControllerContext window:self.window delegate:self];
}
return YES;
}
create a folder and add the following files
main.js
index.tvml
main.js
function launchPlayer() {
var player = new Player();
var playlist = new Playlist();
var mediaItem = new MediaItem("video", "http://trailers.apple.com/movies/focus_features/9/9-clip_480p.mov");
player.playlist = playlist;
player.playlist.push(mediaItem);
player.present();
//player.play()
}
//in application.js
App.onLaunch = function(options) {
launchPlayer();
}
careful with this url in the mediaItem
Set up a template of your choice.
index.tvml
<document>
<alertTemplate>
<title>…</title>
<description>…</description>
<button>
<text>…</text>
</button>
<text>…</text>
</alertTemplate>
</document>
open terminal and navigate to this folder then run
python -m SimpleHTTPServer 8000
make sure the port here is the port in your ObjC url. The Apple examples use 9001.
See these tutorials for more info
http://jamesonquave.com/blog/developing-tvos-apps-for-apple-tv-with-swift/
http://jamesonquave.com/blog/developing-tvos-apps-for-apple-tv-part-2/
One issue I ran into was trying to play a local video file. It wouldn't work and there were constraint issues etc.
It looks like you can't use python to play the videos so either try apache or link to a video on the web.
This SO answer pointed me there.

The best way to play video in your app on AppleTV is going to be AVKit's AVPlayerViewController. If you use AVKit, you get a lot of stuff for free.
https://developer.apple.com/library/ios/documentation/AVFoundation/Reference/AVPlayerViewController_Class/index.html
You simply add that player to the viewController's player property:
// instantiate here or in storyboard
AVPlayerViewController *viewController = [[AVPlayerViewController alloc] initWithNibName:nil bundle:nil];
viewController.player = player;
[self addChildViewController:viewController];
[self.view addSubview:viewController.view];
[viewController didMoveToParentViewController:self];
// setup constraints, etc.
// play the video
[player play];
Also as mentioned below, make sure the video you're trying to play is coming either from an HTTPS connection or that you've disabled App Transport Security by setting the proper flags in the plist.

I didn't like the answers which messed about with subviews etc.
For full-screen playback, I use the following (Non-ARC) code:
// Play the stream
NSString *wifiStreamAddress = #"http://yourmoviefile.m3u8";
AVPlayer *player = [[AVPlayer alloc] initWithURL: [NSURL URLWithString: wifiStreamAddress] ];
AVPlayerViewController *playerViewController = [[AVPlayerViewController alloc] init];
playerViewController.player = player;
// Keep pointers to player and controller using retained properties:
self.player = player;
self.playerViewController = playerViewController;
[player release];
[playerViewController release];
[self presentViewController: playerViewController animated: true completion: ^{
[self.player play];
}];
This works really neat, animating presentation and fading back to previous view when you tap the MENU button. Also, it works great with the remote control using all the standard functions.

Its working for me.
May be helpful for you
-(void)playAction
{
AVPlayerViewController *viewController = [[AVPlayerViewController alloc] initWithNibName:nil bundle:nil];
viewController.player = player;
[self addChildViewController:viewController];
[self.view addSubview:viewController.view];
[viewController didMoveToParentViewController:self];
// play the video
[player play];
}

Swift version
Make a PlayViewController which inherit the AVPlayerViewController.
In the viewcontroller which has play button, add such function
#IBAction func onClickPlay(sender: AnyObject) {
let playerVC = PlayerViewController()
playerVC.playVideo(urlString)
[self.presentViewController(playerVC, animated: true, completion: nil)]
}
In the PlayerViewController
func playVimeoVideo(link : String) {
player = AVPlayer(URL: NSURL(string: link)!)
player?.play()
}
Notice
The question and some answers may be a little misleading so that you might think that only the url with ".mp4" at the end can be played by the Apple TV. I believed so at the first time I saw the post. It is not true. In fact, with AVPlayerViewController you can play Vimeo streaming video! The link to the stream video is not like https://vimeo.com/92655878. It is possible to get it from Vimeo site by extracting it from a json file, which can be downloaded from this link
let link = "https://vimeo.com/api/oembed.json?url=https%3A//vimeo.com/" + videoId
To be able to get correct url for the video, you need to use the Vimeo Pro user access to get the stream link for a specific video.

Related

PhotoEditorSDK configuration

I am trying to configure the photoeditorSDK for iOS, but am struggling.
My current issues are the following:
1. When a user clicks on the brush toolMenuItem, it does not do anything. Other toolMenuItems do what they are supposed to (e.g. Size).
Similarly, when a user adds text through the Text Menu Item, it works, however when they try to resize the text - they can't click it.
I believe these issues are related - that is why I opted them together.
Here's the code snippet used to configure the control:
NSError *dataCreationError;
NSURL *aLocalURL = [NSURL URLWithString:filepath];
NSData *imageData = [NSData dataWithContentsOfFile:aLocalURL.path options:0 error:&dataCreationError];
if (imageData && !dataCreationError) {
PESDKConfiguration *configuration = [[PESDKConfiguration alloc] initWithBuilder:^(PESDKConfigurationBuilder * _Nonnull builder) {
// See Configuration section
}];
NSMutableArray<PESDKPhotoEditMenuItem *> *menuItems = [[PESDKPhotoEditMenuItem defaultItems] mutableCopy];
[menuItems removeLastObject]; // Remove last menu item ('Magic')
PESDKPhotoEditViewController *photoEditViewController = [[PESDKPhotoEditViewController alloc] initWithData:imageData configuration:configuration];
photoEditViewController.delegate = self;
UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:photoEditViewController];
dispatch_async(dispatch_get_main_queue(), ^{
[self.viewController presentViewController:navigationController animated:YES completion:nil];
});
} else if (dataCreationError) {
NSLog(#"Failed to open given path: %#", dataCreationError);
}
This is a bug on our side and will be fixed with the next release, which will go live this week. As a workaround, we updated your subscription. You just need to generate a new license file using our dashboard and replace the existing one in your app. This should fix both issues, but will add the Sticker tool to your menu items. You may remove it just like you did with the Magic tool.
If you have further questions, just let me know!

Gluon Mobile Share Button Implementation

Does Gluon Mobile have any guidance on implementing a share button? My goal is to be able to share a string containing a link to different apps on the phone. At the moment, I need this only for the iOS implementation. I was able to find this link that provides a simple way to do this in Objective-C:
- (IBAction)shareButton:(UIBarButtonItem *)sender
{
NSString *textToShare = #"Look at this awesome website for aspiring iOS Developers!";
NSURL *myWebsite = [NSURL URLWithString:#"http://www.codingexplorer.com/"];
NSArray *objectsToShare = #[textToShare, myWebsite];
UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:objectsToShare applicationActivities:nil];
NSArray *excludeActivities = #[UIActivityTypeAirDrop,
UIActivityTypePrint,
UIActivityTypeAssignToContact,
UIActivityTypeSaveToCameraRoll,
UIActivityTypeAddToReadingList,
UIActivityTypePostToFlickr,
UIActivityTypePostToVimeo];
activityVC.excludedActivityTypes = excludeActivities;
[self presentViewController:activityVC animated:YES completion:nil];
}
Looking at the GoNative application example on the Gluon website, it seems like I can use the above code snippet where needed as the native iOS code. Do I have to update the ios build gradle to account for the UIActivity class mentioned in the first link above?
Update*
I have been able to get this to work based on help in this question here.
However when trying to install the native library, I get this error which is understandable as self is unknown in the scope of the code. How would I be able to do this? Instantiate a popover or dialog and pass the activityVC to it?
/Users/ashishsharma/NetBeansProjects/konfamdbranch/src/ios/n‌​ative/Share.m:25:6: error: use of undeclared identifier 'self' [self presentViewController:activityVC animated:YES completion:nil];
So I was able to solve this using examples on the internet (shown above) along with going through the existing code for the Barcode Scan Service. The issue I was experiencing with the above code was that the present view controller could not be found. However, looking at the bit bucket source for Barcode Scan, I was able to get the root view with the following code:
if(![[UIApplication sharedApplication] keyWindow])
{
NSLog(#"key window was nil");
return;
}
// get the root view controller
UIViewController *rootViewController = [[[UIApplication sharedApplication] keyWindow] rootViewController];
if(!rootViewController)
{
NSLog(#"rootViewController was nil");
return;
}
Then in the code snippet I placed in the question, replace self with rootViewController:
[rootViewController presentViewController:activityVC animated:YES completion:nil];
This leads to the modified code snippet:
#import <UIKit/UIKit.h>
#include "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks/JavaVM.framework/Versions/A/Headers/jni.h"
JNIEXPORT void JNICALL Java_com_gluonhq_charm_down_plugins_ios_IOSShareService_shareMessage
(JNIEnv *env, jclass jClass, jstring jMessage) {
if(![[UIApplication sharedApplication] keyWindow])
{
NSLog(#"key window was nil");
return;
}
// get the root view controller
UIViewController *rootViewController = [[[UIApplication sharedApplication] keyWindow] rootViewController];
if(!rootViewController)
{
NSLog(#"rootViewController was nil");
return;
}
NSString *textToShare = #"Check out this site!";
NSURL *myWebsite = [NSURL URLWithString:#"http://www.google.com/"];
NSArray *objectsToShare = #[textToShare, myWebsite];
UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:objectsToShare applicationActivities:nil];
NSArray *excludeActivities = #[UIActivityTypeAirDrop,
UIActivityTypePrint,
UIActivityTypeAssignToContact,
UIActivityTypeSaveToCameraRoll,
UIActivityTypeAddToReadingList,
UIActivityTypePostToFlickr,
UIActivityTypePostToVimeo];
activityVC.excludedActivityTypes = excludeActivities;
[rootViewController presentViewController:activityVC animated:YES completion:nil];
}
Note I followed the GoNative application to generate my objective-c/ios files correctly.
This leads to a minimal functionality share implementation only because I don't have Facebook installed on the IPhone simulator.

how to autoplay sound when I open the app?

I'm new to xcode .I want to autoplay a sound when I open the app . I put the code in viewDidLoad but when I open other view and go back the sound play again .how can fix this problem ??
You could set a boolean variable to true after the first time you play it. Something like this:
bool soundPlayed = FALSE;
- (void)viewDidLoad {
// play your sound
soundPlayed = true;
}
Or, in your AppDelegate.m, there's probably something like this:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
You could try doing it in there, too.
Do it in - (void)applicationDidBecomeActive:(UIApplication *)applicationor in - (void) applicationDidFinishLaunching:(UIApplication*)application. If you use it in didBecomeActive the app will play the sound if you background it and open it again.
Playing a sound file goes like this:
NSURL* musicFile = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"click"
ofType:#"caf"]];
AVAudioPlayer *click = [[AVAudioPlayer alloc] initWithContentsOfURL:musicFile error:nil];
[click play];
[click release];

How to mute and unmute audio in iPad by tapping a button?

I'd like to know how to make the mute and unmute the audio on my iPad application by tapping a button. I already have a working code in my viewDidLoad method that plays a music when the app is launched. All I need to do is to create a button that will stop the music from playing and also resume it when tapped again.
Here's my code in my viewDidLoad:
- (void)viewDidLoad
{
NSString *path = [[NSBundle mainBundle] pathForResource:#"Bored" ofType:#"mp3"];
AVAudioPlayer* theAudio = [[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
theAudio.delegate = self;
[theAudio play];
[super viewDidLoad];
}
Just look at the AVAudioPlayer API - it's all there: play, pause, volume, etc.

MPMoviePlayerController keeps playing after view did unload?

I have a detail view, and when viewdidload in detailviewcontroller, MPMoviePlayerController allocs and plays an audio, but even if I navigate backto main table, audio is still being played.
How can I stop MPMovieplayercontroller when I navigate back to main table ? This is my MPMoviePlayerController code:
.h
MPMoviePlayerController *player;
.m
- (void)viewDidLoad
{
[super viewDidLoad];
//Get the Movie
NSURL *movieURL = [NSURL URLWithString:#"some link"];
player = [[MPMoviePlayerController alloc] initWithContentURL:movieURL];
//Place it in subview, else it won’t work
player.view.frame = CGRectMake(20, 20, 280, 25);
player.backgroundView.backgroundColor = [UIColor clearColor];
[self.view addSubview:player.view];
// Play the movie.
[player play];
}
I even added following code into viewdidunload method, but didn't work.
- (void)viewDidUnload {
[player stop];
player.initialPlaybackTime = -1;
[player release];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
What do you guys suggest ?
Thanks in advance,
I liked the user experience of viewDidDisappear better than viewWillDisappear. The animation starts and the movie stops after - the audio flows better for me this way.
-(void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
[_moviePlayer stop];
}
I am having a similar issue. I am unable to use "viewDidDisappear" or "viewWillDisappear" because I have a "config" type view that can be opened while the content is playing, and it will trigger those two methods.
EDIT: Found that viewDidUnload and viewWillUnload are not getting called any more (I'm currently on an iOS 6+ device)...
From the documentation:
Availability: iOS (3.0 and later) Deprecated: Views are no longer
purged under low-memory conditions and so this method is never called.
I just created a simple function called unload, and inside the function, set any objects I needed to = nil (I'm using ARC). At the time that I make the call to remove the view, I call the unload function as well. Hope it helps someone.

Resources