IOS-Ask the user for play song in uiwebview media player - ios

If I click on the mp3 url in a UIWebView, It pops the media player to play the mp3 automatically.
But here what I am need is just ask confirmation from the user to play the song in UIWebview media player.Is it possible to access UIWebview media player? If it is how?
Please help me

Yes, it is possible to ask confirmation from the user.
User UIWebView delegate method :
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
self.URL = [request URL];
if (navigationType == UIWebViewNavigationTypeLinkClicked)
{
AVURLAsset* asset;
self.songURL = [NSString stringWithFormat:#"%#",self.URL];
//Check for supported song formatted
if([self.songURL hasSuffix:#".mp3"] ||
[self.songURL hasSuffix:#".wav"] ||
[self.songURL hasSuffix:#".aiff"] ||
[self.songURL hasSuffix:#".aac"] ||
[self.songURL hasSuffix:#".m4a"] ||
[self.songURL hasSuffix:#".m4p"] ||
[self.songURL hasSuffix:#".caf"])
{
asset = [[AVURLAsset alloc]initWithURL:self.URL options:nil];
if(asset != nil)
{
UIActionSheet *actSheet = [[UIActionSheet alloc]
initWithTitle:#"Songs"
delegate:self
cancelButtonTitle:#"Cancel"
destructiveButtonTitle:#"Download"
otherButtonTitles:#"Listen Online", nil];
[actSheet showInView:self.view];
}
[asset release];
return NO;
}
}
return YES;
}
And on UIActionSheetDelegate method:
-(void) actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
if(buttonIndex == 1)
{
[self.webView loadRequest:[NSURLRequest requestWithURL:self.URL]];
}
}

Related

SFSafariViewController does not reopen a webview inline URL link

I have a Webview with inline URL links which are opened with SFSafariViewController, as shown below:
-(BOOL) webView:(UIWebView *)inWeb shouldStartLoadWithRequest:(NSURLRequest *)inRequest navigationType:(UIWebViewNavigationType)inType {
if ( inType == UIWebViewNavigationTypeLinkClicked ) {
if ([SFSafariViewController class] != nil) {
NSString *inR = [[inRequest URL] absoluteString];
NSURL *inReq = [NSURL URLWithString:inR];
SFSafariViewController *safariVC = [[SFSafariViewController alloc] initWithURL:inReq entersReaderIfAvailable:YES];
safariVC.delegate = self;
[self presentViewController:safariVC animated:YES completion:nil];
} else {
[[UIApplication sharedApplication] openURL:[inRequest URL]];
return NO;
}
}
return YES;
}
#pragma mark - SFSafariViewController delegate methods
-(void)safariViewController:(SFSafariViewController *)controller didCompleteInitialLoad:(BOOL)didLoadSuccessfully {
// Load finished
}
-(void)safariViewControllerDidFinish:(SFSafariViewController *)controller {
// Done button pressed
NSLog(#"DONE PRESSED!!!");
}
When I press the DONE button correctly returns to my Webview. The problem is that if I will press again on the same inline link, it does not open with SFSafariViewController but in Webview which is not what i desire. I tried to force Webview reload in safariViewControllerDidFinish but without success.
Could you please help? Thanks!
The code corrected as below (following proposal of beyowulf) and now is working OK:
-(BOOL) webView:(UIWebView *)inWeb shouldStartLoadWithRequest:(NSURLRequest *)inRequest navigationType:(UIWebViewNavigationType)inType {
if ( inType == UIWebViewNavigationTypeLinkClicked ) {
if ([SFSafariViewController class] != nil) {
NSString *inR = [[inRequest URL] absoluteString];
NSURL *inReq = [NSURL URLWithString:inR];
SFSafariViewController *safariVC = [[SFSafariViewController alloc] initWithURL:inReq entersReaderIfAvailable:YES];
safariVC.delegate = self;
[self presentViewController:safariVC animated:YES completion:nil];
return NO;
} else {
[[UIApplication sharedApplication] openURL:[inRequest URL]];
return NO;
}
} else {
return YES;
}
}
#pragma mark - SFSafariViewController delegate methods
-(void)safariViewController:(SFSafariViewController *)controller didCompleteInitialLoad:(BOOL)didLoadSuccessfully {
// Load finished
}
-(void)safariViewControllerDidFinish:(SFSafariViewController *)controller {
// Done button pressed
NSLog(#"DONE PRESSED!!!");
}

Alert before switch to maps if clicking on address in UIWebView

I am using the following code to detect if a link is clicked in a UIWebView and show an alert. So the user needs to confirm to leave the app. The detection for addresses in also active. If the user is tapping on an address you directly switch to the Maps app from Apple. I want to detect this as well to show an alert before switching to the Maps app. How can I detect if an address(location) is clicked in an UIWebView?
-(BOOL) webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
savedLink = [request URL];
if ( ( [ [ savedLink scheme ] isEqualToString: #"http" ] || [ [ savedLink scheme ] isEqualToString: #"https" ]) && ( navigationType == UIWebViewNavigationTypeLinkClicked ) ) {
UIAlertView *leaveApp = [[UIAlertView alloc]initWithTitle:#"Warning!" message:#"You want to leave the app?" delegate:self cancelButtonTitle:#"No" otherButtonTitles:#"Yes", nil];
[leaveApp show];
return NO;
}
return YES;
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
if([title isEqualToString:#"Yes"])
{
[[UIApplication sharedApplication] openURL:savedLink];
}
else if([title isEqualToString:#"No"])
{
//do nothing
}
}
I was expecting something like maps.apple.com but the scheme is called x-apple-data-detectors.
If I am looking for that scheme it is working.
[[savedLink scheme] isEqualToString:#"x-apple-data-detectors"]

How to add another button that directs users to Facebook on uiAlert?

I need to add a button Facebook, Then the action should take user to Facebook, I'm just not sure how to do it from the code below?
-(IBAction)btContinueClick:(id)sender{
if(Level == [list count]){
UIAlertView *info = [[UIAlertView alloc]initWithTitle:#"Good" message:#"Go to facebook?" delegate:self cancelButtonTitle:#"NO" otherButtonTitles:#"Facebook"];
[info show]; //// Change Game End Message
}
}
If you want to go to the native app of Facebook in iOS.
Using delegate method of alertView
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if(buttonIndex == 1) {
NSURL *url = [NSURL URLWithString:#"fb://profile"];
if ([[UIApplication sharedApplication] canOpenURL:url]) { //USE FB NATIVE APP
[[UIApplication sharedApplication] openURL:url];
}
else { //IF THE DEVICE IS UNABLE TO OPEN IN NATIVE APP, USE BROWSER INSTEAD
NSURL *browserURL = [NSURL URLWithString:#"http://www.facebook.com"];
[[UIApplication sharedApplication] openURL:browserURL];
}
}
}
Make sure you have added UIAlertViewDelegate in .h file
-(IBAction)btContinueClick:(id)sender{
if(Level == [list count]){
UIAlertView *info = [[UIAlertView alloc]initWithTitle:#"Good" message:#"Go to facebook?" delegate:self cancelButtonTitle:#"NO" otherButtonTitles:#"Facebook"];
[info show]; //// Change Game End Message
info.delegate=self;
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
if(buttonIndex==1)
{
NSLog(#"Facebook selected.");
NSURL *url = [NSURL URLWithString:#"fb://profile/<id>"]; // provide the app ID
[[UIApplication sharedApplication] openURL:url];
}
}

How to play youtube/vimeo video within the application in iPhone

I am building an application where I want to play video from url like Youtube, Vimeo, Direct url. I am making custom player using AVPlayer to play a video from a direct url of video clip(like www.abc/play.mp4). But later I faced a huge issue to play youtube & vimeo video. And after searching a lot I found these link where it says without using UIWebview I can't play a Youtube link:
Play YouTube videos with MPMoviePlayerController instead of UIWebView
Playing video from youtube link without UIWebView
So I just used this code:
NSString *youTubeVideoHTML = #"<html><head><style>body{margin:0;}</style></head> <body> <div id=\"player\"></div> <script> var tag = document.createElement('script'); tag.src = 'http://www.youtube.com/player_api'; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); var player; function onYouTubePlayerAPIReady() { player = new YT.Player('player', { width:\'100%%\', height:'200px', videoId:\'%#\', events: { 'onReady': onPlayerReady } }); } function onPlayerReady(event) { event.target.playVideo(); } </script> </body> </html>";
NSString *html = [NSString stringWithFormat:youTubeVideoHTML, videoId];
self.embedded_player_view.mediaPlaybackRequiresUserAction = NO;
[self.embedded_player_view loadHTMLString:html baseURL:[[NSBundle mainBundle] resourceURL]];
Now when I click on youtube/Vimeo video link from tableview its playing the video with the default player i.e. quicktime player. Its not running the video within the UIWebview frame itself.
But I want to show the video in the 1st half of the screen i.e my UIWebview frame. Is that possible?
In my app I can see this:
when clicking on red play button I can see the video in full screen in quicktime player like this:
But I want to show the video within the same webView frame not via quick time player. It should play like this:
Same does in MusicTube and PlayTube.
Or is there any other way to achieve the same? Any help will be appreciated. Thanks in advance.
I've used this class just for that.
The video you see inside the UIViewController is playable in its current size.
That's the only code I've used:
UIView *videoContainerView = [[UIView alloc]initWithFrame:CGRectMake(0, 50, 320, 200)];
[self.view addSubview:videoContainerView];
XCDYouTubeVideoPlayerViewController *videoPlayerViewController = [[XCDYouTubeVideoPlayerViewController alloc] initWithVideoIdentifier:#"_OBlgSz8sSM"];
[videoPlayerViewController presentInView:videoContainerView];
[videoPlayerViewController.moviePlayer play];
For Vimeo player you can check this link https://github.com/lilfaf/YTVimeoExtractor it plays the video in real player and if you want to run the video in uiwebview,here is the code for that https://stackoverflow.com/a/15918011/1865424.
Pass you URL of YouTube Video in “urlStr”.
//In .h file
UIWebView *videoView;
// In .m file
videoView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 385)];
[self embedYouTube :urlStr frame:CGRectMake(0, 0, 320, 385)];
[self.view addSubview:videoView];
// methos to embed URL in HTML & load it to UIWebView
- (void)embedYouTube:(NSString*)url frame:(CGRect)frame
{
NSString* embedHTML = #”\
<html><head>\
<style type=\”text/css\”>\
body {\
background-color: transparent;\
color: white;\
}\
</style>\
</head><body style=\”margin:0\”>\
<embed id=\”yt\” src=\”%#\” type=\”application/x-shockwave-flash\” \
width=\”%0.0f\” height=\”%0.0f\”></embed>\
</body></html>”;
NSString* html = [NSString stringWithFormat:embedHTML, url, frame.size.width, frame.size.height];
if(videoView == nil) {
videoView = [[UIWebView alloc] initWithFrame:frame];
[self.view addSubview:videoView];
}
[videoView loadHTMLString:html baseURL:nil];
}
Courtsey :- http://nanostuffs.com/Blog/?p=641
Hope This Will Help You Out.
If this doesn't help you out please check out these links:-
http://blog.softwareispoetry.com/2010/03/how-to-play-youtube-videos-in-your.html
https://gist.github.com/darkredz/5334409
http://maniacdev.com/2012/02/open-source-library-for-easily-playing-a-youtube-video-in-an-mpmovieplayer
If you wanna play youtube, here's a link to youtube player project on github, It's really helpful. and yes it is possible to play it in your uiwebview, just give the webview the url and tell it to load, it shouldn't open in the default player, as far as i believe at least.
I don't know about the Vimeo but for youtube videos you can use HCYouTubeParser to fetch mp4 urls for the youtube videos which can be later played on AVPlayer or MpMoviePlayerVC as per requirements.
I used youtube and vimeo in my Project, I share my codings for you it will very hopeful for you
in my view controller.m
//Button action
- (IBAction)importAudioClip:(id)sender
{
flag = 0;
customActionSheet = [[UIActionSheet alloc]initWithTitle:#"Select Audio/Video from:" delegate:self cancelButtonTitle:#"Cancel" destructiveButtonTitle:nil otherButtonTitles:#"YouTube",#"Vimeo", nil];
[customActionSheet showInView:self.view];
}
#pragma ActionSheet Delegate Methods
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSLog(#"CLiekc button is %i",buttonIndex);
if([actionSheet.title isEqualToString:#"Select Audio/Video from:"])
{
if (buttonIndex == 0)
{
videoStatus=0;
webView.hidden = NO;
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.youtube.com"]]];
NSLog(#"Taking from Youtube");
}
else if (buttonIndex == 1)
{
videoStatus=1;
UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:#"Vimeo" message:#"Please enter Vimeo Username" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"OK", nil];
alertView.tag=123;
alertView.alertViewStyle = UIAlertViewStylePlainTextInput;
[alertView show];
}
}
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (alertView.tag==123)
{
if (buttonIndex==1)
{
templateText=[[UITextField alloc]init];
templateText = [alertView textFieldAtIndex:0];
templateText.autocapitalizationType=UITextAutocapitalizationTypeWords;
templateText.delegate=self;
if ([templateText.text length]!=0)
{
NSString *str=[templateText.text capitalizedString];
NSLog(#"Str== %#",str);
[self getVimeoDetails:str];
}
}
}
}
-(void)getVimeoDetails:(NSString*)userName
{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://vimeo.com/api/v2/%#/videos.json",userName]]];
[request setHTTPMethod:#"GET"];
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];
NSLog(#"The value is==%#",resSrt);
vimeoDetailsArray =(NSArray*) [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&err];
NSLog(#"jsonObject== %i",[vimeoDetailsArray count]);
NSString *theReply = [[NSString alloc] initWithBytes:[responseData bytes] length:[responseData length] encoding: NSASCIIStringEncoding];
NSLog(#"the reply == %#",theReply);
if(response)
{
if (vimeoDetailsArray==NULL)
{
NSLog(#"its Null");
NSLog(#"null response== %#",response);
// UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Alert!!!" message:[NSString stringWithFormat:#"%#",theReply] delegate:self
// cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
// [alert show];
// [self performSelector:#selector(showAlertMessage:theReply withTitle:#"Alert!!!") withObject:nil afterDelay:5];
vimeoVideoTable.hidden=YES;
[self showAlertMessage:[NSString stringWithFormat:#"%#",theReply] withTitle:#"Alert!!!"];
}
else
{
[self createTableView];
vimeoVideoTable.hidden=NO;
[vimeoVideoTable reloadData];
NSLog(#"got response== %#",response);
}
}
else
{
NSLog(#"faield to connect");
}
if ([responseData length] == 0 && err == nil)
{
NSLog(#"Nothing was downloaded.");
}
else if (err != nil){
if ([[err description] rangeOfString:#"The Internet connection appears to be offline"].location != NSNotFound)
{
NSLog(#"string does not contain ");
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Alert!!!" message:#"Please Check your Internet Connection" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
NSLog(#"Error = %#", err);
}
}
-(void)createTableView
{
if (vimeoVideoTable !=nil)
{
[vimeoVideoTable removeFromSuperview];
vimeoVideoTable=nil;
}
vimeoVideoTable=[[UITableView alloc]initWithFrame:CGRectMake(10, 20, 300, self.view.bounds.size.height-100)];
[vimeoVideoTable setDelegate:self];
[vimeoVideoTable setHidden:YES];
[vimeoVideoTable setDataSource:self];
[self.view addSubview:vimeoVideoTable];
//[vimeoVideoTable reloadData];
}
I definitely suggest youtube_ios_player_helper, "sponsored by" Google.
import youtube_ios_player_helper
class YTViewController: YTPlayerViewDelegate {
#IBOutlet weak var player: YTPlayerView!
// MARK: - Public properties -
var videoID = "k_okcNVZqqI"
// MARK: - View life cycle -
override func viewDidLoad() {
super.viewDidLoad()
self.player.delegate = self
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.load()
self.player.fadeOut()
}
/**
Play video with the relative youtube identifier.
*/
func load() {
Utils.showHUD(self.view)
let options = ["playsinline" : 1]
self.player.loadWithVideoId(self.videoID, playerVars: options)
}
/**
Stop video playing.
*/
func stop() {
}
// MARK: - YOUTUBE video player delegate -
func playerViewDidBecomeReady(playerView: YTPlayerView) {
self.player.playVideo()
}
func playerView(playerView: YTPlayerView, didChangeToState state: YTPlayerState) {
switch state {
case .Playing:
self.player.fadeIn(duration: 0.5)
Utils.hideHUD(self.view)
print("Started playback")
break;
case .Paused:
print("Paused playback")
break;
default:
break;
}
}
}
Use this
NSMutableString *html = [[NSMutableString alloc] initWithCapacity:1] ;
[html appendString:#"<html><head>"];
[html appendString:#"<style type=\"text/css\">"];
[html appendString:#"body {"];
[html appendString:#"background-color: transparent;"];
[html appendString:#"color: white;"];
[html appendString:#"}"];
[html appendString:#"</style>"];
[html appendString:#"</head><body style=\"margin:0\">"];
[html appendString:#"<iframe src=\"//player.vimeo.com/video/84403700?autoplay=1&loop=1\" width=\"1024\" height=\"768\" frameborder=\"0\" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>"];
[html appendString:#"</body></html>"];
[viewWeb loadHTMLString:html baseURL:urlMovie];
I used the following method to solve the same problem successfully.
Use youtube-ios-player-helper and add the code:
[_playerView loadWithVideoId:#"DmTzboEqfNk" playerVars:#{
#"playsinline" : #1
}];
You can find more vars in Youtube > IFrame API.
I have used WKWebView in storyboard with constraints and added code :
func playVideo() {
if yourLink.lowercased().contains("youtu.be"){
getVideo(videoCode: yourVideoCode)
if let range = yourLink.range(of: "be/"){
let videoId = yourLink[range.upperBound...].trimmingCharacters(in: .whitespaces)
getVideo(videoCode: videoId)
}
} else if yourLink.lowercased().contains("youtube.com"){
if let range = yourLink.range(of: "?v="){
let videoId = yourLink[range.upperBound...].trimmingCharacters(in: .whitespaces)
getVideo(videoCode: videoId)
}
} else if yourLink.lowercased().contains("vimeo.com") {
let url: NSURL = NSURL(string: yourLink)
webKitView.contentMode = UIViewContentMode.scaleAspectFit
webKitView.load(URLRequest(url: url as URL))
}
}
func getVideo(videoCode: String) {
guard
let url = URL(string: "https://www.youtube.com/embed/\(videoCode)")
else { return }
webKitView.load(URLRequest(url: url))
}
To get videoId from youtube/Vimeo links, please refer to :
Youtube Video Id from URL - Swift3
Regex to get vimeo video id in swift 2
Hope will help! :)

get urls of 2 uiwebview's and put to their own adress bar

In my app I have 2 UIWebView's and 2 Adress Bar tat called WebView and WebView2, webAdress and webAdress2. I need to get url from WebView and put it to webAdress, and from WebView2 and put it to webAdress2.
When I use this code, the URL updates appears only in first webAdress, url from WebView2 apperas in first webAdress too. Moreover, all pages from WebView2 starts to be load in WebView.
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
//CAPTURE USER LINK-CLICK.
if (navigationType == UIWebViewNavigationTypeLinkClicked) {
NSURL *URL = [request URL];
if ([[URL scheme] isEqualToString:#"http"]) {
[webAdress setText:[URL absoluteString]];
[self gotoAddress:nil];
}
return NO;
}
return YES;
}
- (BOOL)webView2:(UIWebView*)webView2 shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
//CAPTURE USER LINK-CLICK.
if (navigationType == UIWebViewNavigationTypeLinkClicked) {
NSURL *URL = [request URL];
if ([[URL scheme] isEqualToString:#"http"]) {
[webAdress2 setText:[URL absoluteString]];
[self gotoAddress2:nil];
}
return NO;
}
return YES;
}
I guess you are in need of only one delegate method. Check which webview has triggered this delegate method and perform actions depend on this:
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
//CAPTURE USER LINK-CLICK.
if (navigationType == UIWebViewNavigationTypeLinkClicked) {
NSURL *URL = [request URL];
if ([[URL scheme] isEqualToString:#"http"]) {
if (webView == webView1)
[webAdress setText:[URL absoluteString]];
if (webView == webView2)
[webAdress2 setText:[URL absoluteString]];
[self gotoAddress2:nil];
}
return NO;
}
return YES;
}
Just set for all web views delegate as self, and all you can handle all actions in this method.

Resources