How to get the url of currently playing video in UIWebview - ios

Is there any way to get the link of currently playing video.I am loading m.youtube.com .For some videos it is not even entering the delegates.I tried using a NStimer as well.But for some videos it is not the clicked url

There is a hacky way of doing it by listening for the AVPlayerItemBecameCurrentNotification notification. This notification is fired when a UIWebView shows the media player, and it sends an AVPlayerItem as the notification's object.
For example:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(playerItemBecameCurrent:)
name:#"AVPlayerItemBecameCurrentNotification"
object:nil];
-(void)playerItemBecameCurrent:(NSNotification*)notification {
AVPlayerItem *playerItem = [notification object];
if(playerItem == nil) return;
// Break down the AVPlayerItem to get to the path
AVURLAsset *asset = (AVURLAsset*)[playerItem asset];
NSURL *url = [asset URL];
NSString *path = [url absoluteString];
}
This works for any video (and audio). However, I noticed you mentioned YouTube - it's worth pointing out Apple WILL reject your app if it has the ability to download YouTube videos AT ALL, because it's against YouTube's Terms of Service.

This one is for swift version:
//Add NSNotificationcenter for current playing song
override func viewDidAppear(_ animated: Bool) {
NotificationCenter.default.addObserver(self, selector:#selector(playerItemBecameCurrent), name:NSNotification.Name(rawValue: "AVPlayerItemBecameCurrentNotification"), object:nil)
}
//Fetch path from notificationcenter
#objc func playerItemBecameCurrent(notification:NSNotification){
let playerItem:AVPlayerItem = notification.object as! AVPlayerItem
let asset:AVURLAsset=playerItem.asset as! AVURLAsset
let url = asset.url
let path = url.absoluteString
print(path)
}

Related

AVPlayer cannot play mp3-format file loaded by AVURLAsset with option AVURLAssetPreferPreciseDurationAndTimingKey set to true on iOS 14

While testing my app on iOS 14, I found some mp3-format files not working properly. There's no error from start to end, but sounds only heard in the very beginning and muted in the following seconds.
Here are sample codes to reproduce.
NSURL *url = [NSURL URLWithString:urlString];
BOOL preferPreciseDuration = YES;
NSDictionary *options = #{AVURLAssetPreferPreciseDurationAndTimingKey: #(preferPreciseDuration)};
AVURLAsset *asset = [AVURLAsset URLAssetWithURL:url options:options];
AVPlayerItem *playerItem = [AVPlayerItem playerItemWithAsset:asset];
[playerItem addObserver:self forKeyPath:#"status" options:NSKeyValueObservingOptionInitial|NSKeyValueObservingOptionNew context:nil];
player = [AVPlayer playerWithPlayerItem:playerItem];
[player play];
I have looked into it for some time and found:
This problem only occurs on iOS 14+.
If I omit AVURLAssetPreferPreciseDurationAndTimingKey option, everything works fine.
It seems to be server-related, I have tested two URLs hosting exact same file, but sample1 works while sample1 doesn't.
On the same server, file1 works while file2 doesn't.
I have recently implement audio features in my application it's working in iOS 14+ too.
var player: AVAudioPlayer?
let url = Bundle.main.url(forResource: "zapsplat_emergency_nuclear_power_station_meltdown_alarm_42849", withExtension: "mp3")!
do {
player = try AVAudioPlayer(contentsOf: url)
guard let player = player else { return }
player.prepareToPlay()
player.play()
} catch let error as NSError {
print(error.description)
}

How can I get current audio URL playing inside my app from WKWebView?

I have a WKWebView and I am checking if audio is playing using
[[AVAudioSession sharedInstance] isOtherAudioPlaying]
I tried to get some information about it using :
[MPNowPlayingInfoCenter defaultCenter] nowPlayingInfo]
but it was nil.
Then I tried:
[[MPMusicPlayerController systemMusicPlayer] nowPlayingItem]
and it was also nil.
How can I get URL of current playing audio?
You need to subscribe on notification :
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(playerItemBecameCurrent:)
name:#"AVPlayerItemBecameCurrentNotification"
object:nil];
And then do this inside method playerItemBecameCurrent
-(void)playerItemBecameCurrent:(NSNotification*)notification {
AVPlayerItem *playerItem = [notification object];
if(playerItem == nil) return;
// Break down the AVPlayerItem to get to the path
AVURLAsset *asset = (AVURLAsset*)[playerItem asset];
NSURL *url = [asset URL];
NSString *path = [url absoluteString];}
As you can already detect when the audio is being played I think that the solution for you would be implementing decidePolicyForNavigationAction method from the WKNavigationDelegate.
You can combine the information provided by this delegate method that will be called whenever a link is clicked associated with the audio detection the you have already done.

How to play YouTube content on tvOS

How would one play a YouTube video on Apple tvOS?
YouTube's embed feature works in iOS 9 as the OS has a UIWebView we can embed it into.
The new tvOS does not include a UIWebView so I cannot see a way to embed the YouTube video.
UIWebView and MPMoviePlayerController are not available for tvOS. Our next option is to use AVPlayer to play YouTube videos.
AVPlayer cannot play a YouTube video from a standard YouTube URL, ie. https://www.youtube.com/watch?v=8To-6VIJZRE. It needs a direct URL to the video file. Using HCYoutubeParser we can accomplish exactly that. Once we have the URL we need, we can play it with our AVPlayer like so:
NSString *youTubeString = #"https://www.youtube.com/watch?v=8To-6VIJZRE";
NSDictionary *videos = [HCYoutubeParser h264videosWithYoutubeURL:[NSURL URLWithString:youTubeString]];
NSString *urlString = [NSString stringWithFormat:#"%#", [videos objectForKey:#"medium"]];
AVAsset *asset = [AVAsset assetWithURL:[NSURL URLWithString:urlString]];
AVPlayerItem *avPlayerItem = [[AVPlayerItem alloc]initWithAsset:asset];
AVPlayer *videoPlayer = [AVPlayer playerWithPlayerItem:avPlayerItem];
AVPlayerLayer *avPlayerLayer = [AVPlayerLayer playerLayerWithPlayer:videoPlayer];
avPlayerLayer.frame = playerView.layer.bounds;
[playerView.layer addSublayer:avPlayerLayer];
[videoPlayer play];
Note that this is NOT allowed under YouTube's TOS. Use it at your own risk. Your app may stop working at any point if YouTube notices you are not following the TOS or if YouTube changes the embed code it generates.
Swift 2.0 version of Daniel Storm's answer:
let youTubeString : String = "https://www.youtube.com/watch?v=8To-6VIJZRE"
let videos : NSDictionary = HCYoutubeParser.h264videosWithYoutubeURL(NSURL(string: youTubeString))
let urlString : String = videos["medium"] as! String
let asset = AVAsset(URL: NSURL(string: urlString)!)
let avPlayerItem = AVPlayerItem(asset:asset)
let avPlayer = AVPlayer(playerItem: avPlayerItem)
let avPlayerLayer = AVPlayerLayer(player: avPlayer)
avPlayerLayer.frame = CGRectMake(0, 0, self.view.frame.width, self.view.frame.height);
self.view.layer.addSublayer(avPlayerLayer)
avPlayer.play()
XCDYouTubeKit has been a popular way to directly play a YouTube video on iOS for a while, and the developer recently updated it to support the new AppleTV.
Here's the code from the Objective-C example:
AVPlayerViewController *playerViewController = [AVPlayerViewController new];
[self presentViewController:playerViewController animated:YES completion:nil];
__weak AVPlayerViewController *weakPlayerViewController = playerViewController;
[[XCDYouTubeClient defaultClient] getVideoWithIdentifier:playlistItem.snippet.resourceId.videoId completionHandler:^(XCDYouTubeVideo * _Nullable video, NSError * _Nullable error) {
if (video)
{
NSDictionary *streamURLs = video.streamURLs;
NSURL *streamURL = streamURLs[XCDYouTubeVideoQualityHTTPLiveStreaming] ?: streamURLs[#(XCDYouTubeVideoQualityHD720)] ?: streamURLs[#(XCDYouTubeVideoQualityMedium360)] ?: streamURLs[#(XCDYouTubeVideoQualitySmall240)];
weakPlayerViewController.player = [AVPlayer playerWithURL:streamURL];
[weakPlayerViewController.player play];
}
else
{
[self dismissViewControllerAnimated:YES completion:nil];
}
}];
Swift example here.
Sadly, even an Apple Staff person echoed the “negative” on this. From an Apple Developer Forums thread on the topic:
There is no support for WebViews on tvOS, and so an iframe implementation will not work. TVML does not offer this capability.
After some trying I'm happy to announce that:
youtube://watch/video_id
will open the YouTube app and play the YouTube video.
Enjoy.
As an addition to Daniel Storm's answer, you can also achieve this with the new TVML language using the code:
<lockup videoURL="http://mp4-url.mp4">
<img src="video thumbnail.jpg" />
</lockup>
(for this to work you'll need the direct video file (mp4) which also is not allowed by the Youtube TOS)
EDIT, found also the .JS solution:
How do I play a video on tvOS for Apple TV?
I used this one https://cocoapods.org/pods/youtube-parser
Youtube.h264videosWithYoutubeURL(testURL) { (videoInfo, error) -> Void in
if let videoURLString = videoInfo?["url"] as? String,
videoTitle = videoInfo?["title"] as? String {
print("\(videoTitle)")
print("\(videoURLString)")
self.playVideo(videoURLString)
}
}

Get downloadable URL(Resource URL) from DailyMotion Videos & other sites?

I need to Download videos from online video hosting sites(i.e. YouTube, DailyMotion, vimeo etc.) to my iOS application.
Recently i am getting video URL from UIWebView as user try to play any video in it. And after getting resource url(url of video which saved at some online path) and try to download it.
i had done it in YouTube by below stuff:
NSString *resourceUrlStr ;
NSString *urlStr = #"function getURL() { return document.getElementsByTagName('VIDEO')[0].src; } getURL();";
resourceUrlStr = [myWebViewObject stringByEvaluatingJavaScriptFromString: urlStr];
This stuff only works for YouTube videos, Where resourceUrlStr provide me url of video resource.
But when i try this stuff for DailyMotion & other video hosting websites, It doesn't return me resource video url.
Any guesses? Or idea?
There are several techniques to perform it.
My prefered technique is,
When Player in WebView start playing a Video You need to set below code for notification :
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:YES];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(myVideoPlayedInFullscreenFirstTime:)
name:#"AVPlayerItemBecameCurrentNotification"
object:nil];
}
-(void)myVideoPlayedInFullscreenFirstTime:(NSNotification*)aNotification {
AVPlayerItem *playerItem = [aNotification object];
if(playerItem == nil) return;
// Break down the AVPlayerItem to get to the path
AVURLAsset *asset = (AVURLAsset*)[playerItem asset];
NSURL *downloadebaleVideoUrl = [asset URL];
/* now, You can download video by above URL.
In some cases it will give you “.m3u” file location.
You can go through it & get All videos from that list.
For DailyMotion there is one library on GitHub:
[For DailyMotion](https://github.com/oikyn/ExtractVideoURLManager)
*/
}
Swift version of solution suggested by #KunalParekh is:
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.myVideoPlayedInFullscreenFirstTime), name: "AVPlayerItemBecameCurrentNotification", object: nil)
}
func myVideoPlayedInFullscreenFirstTime(aNotification: NSNotification) {
var playerItem = aNotification.object
if playerItem == nil {
return
}
let asset:AVURLAsset = playerItem?.asset as! AVURLAsset
var downloadebaleVideoUrl = asset.URL
print("downloadable video url is: \(downloadebaleVideoUrl)")
}
Do remember to import AVFoundation

Detecting and intercepting video playback in UIWebView

I would like to intercept a click in an UIWebView and then use the URL of the video. How is this possible? I found a somewhat similar post which pointed met to the
webView:shouldStartLoadWithRequest:navigationType:
delegate. I cant seem to get the loaded url of the video with this delegate.
I am trying to get the code working in iOS8
There is a hacky way of finding the URL by listening for the AVPlayerItemBecameCurrentNotification notification. This notification is fired when a UIWebView shows the media player, and it sends an AVPlayerItem as the notification's object.
For example:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(playerItemBecameCurrent:)
name:#"AVPlayerItemBecameCurrentNotification"
object:nil];
-(void)playerItemBecameCurrent:(NSNotification*)notification {
AVPlayerItem *playerItem = [notification object];
if(playerItem == nil) return;
// Break down the AVPlayerItem to get to the path
AVURLAsset *asset = (AVURLAsset*)[playerItem asset];
NSURL *url = [asset URL];
NSString *path = [url absoluteString];
}
This works for any video (and audio). However it is worth nothing that this is fired after the media player has loaded, so you can't stop the player from launching at this point (if that was your intention).
If the above solution doesn't work for anyone then try listening to AVPlayerItemNewAccessLogEntry rather than AVPlayerItemBecameCurrentNotification. AVPlayerItemNewAccessLogEntry seems to be called afterwards and is where I was able to set the info.

Resources