passing video url using json in ios - ios

hi I'm trying to view the videos from my server for that i have stored the video url in mysql database
using the json and php code I'm passing the url to the iOS but now I'm getting some problem here
previously using this same format fetching the images from my server but now i want to view the videos this is the first time im working on the videos not to able to get it
this is the code which i used to fetch the url form database and liking to the ios nsurl format
tabecell.m file code:
#import "vediopoliticalCell.h"
#import "vedios.h"
#implementation vediopoliticalCell
//#synthesize movieplayer,titile;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
}
return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
-(void)setDataSource:(vedios *)inVideosObj
{
self.titile.text = inVideosObj.title;
NSURL *url =[NSURL URLWithString:inVideosObj.video];
NSURLRequest *request =[NSURLRequest requestWithURL:url];
connection =[[NSURLConnection alloc] initWithRequest:request delegate:self];
self.responseData = [[NSMutableData alloc]init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;
{
[self.responseData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;
{
MPMoviePlayerController *play = [[MPMoviePlayerController alloc]initWithContentURL:self.responseData];
}
In this code:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;
{
MPMoviePlayerController *play = [[MPMoviePlayerController alloc]initWithContentURL:self.responseData];
}
im getting a waring called:
Incompatible pointer types sending 'NSMutableData ' to parameter of type Nsurl
previously for the image i using this code:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;
{
UIImage *image = [UIImage imageWithData:self.responseData];
self.thumbImageView.image = image;
}
now i dont know how to use for the videos please can anyone help me with this
thanks in advance

self.responseData is NSMutableData but MPMoviePlayerController needs url to load the video.
So, first you have to get url-string from data.
NSString *url =[NSString stringWithUTF8String:[responseData bytes]]
MPMoviePlayerController *play = [[MPMoviePlayerController alloc]initWithContentURL:[NSURL urlWithString:url]];
//Now present the MPMoviePlayerController

Try this
In setDataSource: method
-(void)setDataSource:(vedios *)inVideosObj
{
self.titile.text = inVideosObj.title;
NSURL *url =[NSURL URLWithString:inVideosObj.video];
MPMoviePlayerViewController *videoDeatilView = [[MPMoviePlayerViewController alloc] initWithContentURL:url];
//now you can present this videoDeatilView and
//[videoDeatilView.moviePlayer play]; will play the video
}

Related

Using AVPlayer and AVPlayerViewController, but audio and video not present

My code looks like this:
_player = [AVPlayer playerWithURL:destination];
_playerVC = [AVPlayerViewController new];
_playerVC.player = _player;
dispatch_async(dispatch_get_main_queue(), ^{
[self presentViewController:_playerVC animated:YES completion:^{
[_player play];
}];
});
_player represents AVPlayer and _playerVC represents AVPlayerViewController. I have strong global references to these objects.
Using terminal, I played the file located at the destination (open -a quicktime\ player destinationURLAbsoluteString) and saw the file is properly loaded since it was playing.
It is a m4v file. I have played a m4a file and it properly gave me audio. I have also substituted the url I have for destination to some remote url and that worked for video. This leads me to believe it has something to do with my video. What's weird is that my AVPlayerViewController does show a black screen with all the normal controls, and even shows the video is 2 minutes and 23 seconds. Upon opening the video file manually, I can see that it is also 2 minutes and 23 seconds.
I can forward through the video properly by dragging the white dot indicative of the video's position, but I never hear anything, nor do I see anything but the black screen and controls.
TL;DR
NSLog(#"Destination: %#",destination);
prints: file:///Users/MyLogin/Library/Developer/CoreSimulator/Devices/694F4C94-F785-4931-A312-4C3E7DE8673A/data/Containers/Data/Application/76C923BE-5B25-41F7-9145-63414657FDF6/Documents/mzvf_5914002519860647075.640x352.h264lc.D2.p.m4v
All in all, it looks like I'm properly retrieving the video, but for some reason my player controller is completely black and void of audio. Any help is much appreciated.
Source Code:
.m file:
#import "ViewController.h"
#import "View2ViewController.h"
#import <AVKit/AVKit.h>
#import <AVFoundation/AVFoundation.h>
#interface ViewController ()
#property NSDictionary *requestedSong;
#property (strong) AVPlayer *player; //Declare Globally
#property (strong) AVPlayerViewController *playerVC;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor yellowColor];
UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 200, 50)];
button.center = self.view.center;
button.backgroundColor = [UIColor blueColor];
[button setTitle:#"Query Songs" forState:UIControlStateNormal];
[button addTarget:self action:#selector(buttonClicked) forControlEvents:UIControlEventTouchDown];
[self.view addSubview:button];
UIButton *button2 = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 200, 50)];
button2.center = CGPointMake(button.center.x, button.center.y + 200);
button2.backgroundColor = [UIColor blueColor];
[button2 setTitle:#"Listen to the first song" forState:UIControlStateNormal];
[button2 addTarget:self action:#selector(button2Clicked) forControlEvents:UIControlEventTouchDown];
[self.view addSubview:button2];
}
-(void)button2Clicked{
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc]init]];
NSURL *url = [NSURL URLWithString:[_requestedSong objectForKey:#"previewUrl"]];
NSMutableURLRequest *req = [[NSMutableURLRequest alloc]initWithURL:url];
NSURLSessionDownloadTask *task = [session downloadTaskWithRequest:req];
[task resume];
}
-(void)buttonClicked{
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc]init]];
NSURL *url = [NSURL URLWithString:#"https://itunes.apple.com/search?media=movie&entity=movie&term=Mad"];
NSMutableURLRequest *req = [[NSMutableURLRequest alloc]initWithURL:url];
NSURLSessionDataTask *task = [session dataTaskWithRequest:req];
[task resume];
}
-(NSURL*)localFilePathForURL:(NSURL *) previewUrl{
//get the directory to use
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, true) objectAtIndex:0];
//create the full path
NSString *fullPath = [documentsPath stringByAppendingPathComponent:previewUrl.lastPathComponent];
//append the filename and append to document path url
return [NSURL fileURLWithPath:fullPath];
}
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location{
NSURL* originalURL = downloadTask.originalRequest.URL;
NSURL *destination = [self localFilePathForURL:originalURL];
NSLog(#"Destination: %#",destination);
NSFileManager *defaultFileManager = [NSFileManager defaultManager];
if([defaultFileManager fileExistsAtPath:destination.absoluteString]){
[defaultFileManager removeItemAtURL:destination error:nil];
}
NSError *error;
#try {
[defaultFileManager copyItemAtURL:location toURL:destination error:&error];
} #catch (NSException *exception) {
NSLog(#"copy caught with exception: %#",exception);
return;
}
dispatch_async(dispatch_get_main_queue(), ^{
_player = [AVPlayer playerWithURL:destination];
_playerVC = [AVPlayerViewController new];
_playerVC.player = _player;
[self presentViewController:_playerVC animated:YES completion:^{
[_player play];
}];
});
NSLog(#"Hello");
}
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
didReceiveData:(NSData *)data{
NSError *error2;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:1 error:&error2];
_requestedSong = [[dict valueForKey:#"results"] objectAtIndex:0];
NSLog(#"Searched: %#",[_requestedSong objectForKey:#"trackName"]);
}
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response
completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler {
completionHandler(NSURLSessionResponseAllow);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
.h file:
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController <NSURLSessionDataDelegate, NSURLSessionDownloadDelegate>
#end
UPDATE:
Upon using the actual URL endpoint for mad max instead of downloading the video, it also displays a blank video. This must mean there's something weird about the format of the video or how it interacts with the AVPlayer.
You should setup observer for AVPlayer status to call play only when it will be ready to play.
How to do it - check answers here: AVPlayer And Local Files
check the following
if ((_playerVC.player.rate != 0) && (_playerVC.player.error == nil)) {
// player is playing
} else {
// Something wrong
}
also you can observe the rate property of the player. More info here

using buttons to open webviews

Hey guys, i'm trying to make the buttons on my project to open a different webview url. I'm new to iOS programming, but i've used andriod programming. Is this possible? I've a ready created another webview view that sits in the supporting files folder.
Here is my code below
Viewcontroller.m
#import "ViewController.h"
#implementation ViewController
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
-(void)viewDidLoad
{
NSString *urlString = #"http://www.athletic-profile.com/Application";
//Create a URL object.
NSURL *url = [NSURL URLWithString:urlString];
//URL Requst Object
NSURLRequest *webRequest = [NSURLRequest requestWithURL:url];
//Load the request in the UIWebView.
[webView loadRequest:webRequest];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
#synthesize webView;
#end
Add a button to your View then give a connection to it. In the action method just write your code
-(IBAction*)yourButtonActionMethod:(id)sender
{
[UIWebView *aWebView =[[UIWebView alloc] initWithFrame:CGRectMake(x,y,width,height)];
aWebView.delegate=nil;
NSString *urlString = #"http://www.athletic-profile.com/Application";
//Create a URL object.
NSURL *url = [NSURL URLWithString:urlString];
//URL Requst Object
NSURLRequest *webRequest = [NSURLRequest requestWithURL:url];
//Load the request in the UIWebView.
[aWebView loadRequest:webRequest];
[self.view addSubView:aWebView];
}
Firstly you can drag & drop UIButton in First Class & create action of that Button then create a new class for UIWebView in which you want to open you url named your choice which is subclass of UIViewController then into your .Xib or Storyboard you just drag & drop the UIWebView then create outlet of UIWebView after you write this code in first class of that button's action :-
- (IBAction *) firstButton:(id) sender
{
NSString *urlString = #"http://www.athletic-profile.com/Application";
//Create a URL object.
NSURL *url = [NSURL URLWithString:urlString];
//URL Request Object
NSURLRequest *webRequest = [NSURLRequest requestWithURL:url];
//Load the request in the UIWebView.
[webView loadRequest:webRequest];
}

Use of Undeclared indentifier

An error came up with [mpc [[MPMoviePlayerController alloc]][[initWithContentURL:url]]]; it says initWithContentURL is a Undeclared Indentifier. How do I fix that?
import "ViewController.h"
#interface ViewController ()
{
MPMoviePlayerController *mpc;
}
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)playButton:(id)sender {
NSString *stringpath;[[NSBundle mainBundle]pathForResource:#"Lake Weekend September 13-14" ofType:#"m4v"];
NSURL *url = [[[NSURL fileURLWithPath:stringpath]
[mpc [[MPMoviePlayerController alloc]][[initWithContentURL:url]]];
[mpc setMovieSourceType:MPMovieSourceTypeFile];
[[self view ]addSubview:mpc.view];
[mpc setFullscreen:YES];
[mpc play];
}
#end
Your alloc/init of mpc looks all wrong. That line looks all garbled to me. I think that that line should read something like:
mpc=[[MPMoviePlayerController alloc] initWithContentURL: url];
You haven't declared url before using it? You're trying to use it within the declaration of it...
NSURL *url = [[[NSURL fileURLWithPath:stringpath]
[mpc [[MPMoviePlayerController alloc]][[initWithContentURL:url]]];
You should at least have a semi colon after the first line.. then you will be able to use url. Plus you would need to sort out your additional brackets, try this..
NSURL *url = [NSURL fileURLWithPath:stringpath];
mpc = [[MPMoviePlayerController alloc]initWithContentURL:url];

Play mp4 video(url) which was protected by Windows authentication, using MPMoviePlayerController

I have an .mp4 video(url) which was protected by Windows authentication. I would like to play using MPMoviePlayerController.
I've implemented some code, and I'm sure I'm close!
So, I'm trying to "unlock" the mp4 url using NSURLConnection. It works, but when I try to access the same url with initWithContentURL, it doesn't work. (it cannot "see" that I've entered the info previously.
So, the question was; how do I onlock a folder/url permanently, OR how can I provide MPMoviePlayerController a NSURLConnection instead of NSURL.
1- So, here's the steps I've taken:
- (void)viewDidLoad{
[super viewDidLoad];
//[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"]]];
[self tryConnection];
}
2--> I'm trying to access the protected URL(this was working)
- (void) tryConnection{
NSURLRequest* request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://www.abcd.com/_develop/video/01.mp4"]];
NSURLConnection* connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
//[request release];
//[connection release];
}
3- this was called properly
- (BOOL)connection:(NSURLConnection*)conn canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace*)protectionSpace {
if([[protectionSpace authenticationMethod] isEqualToString:NSURLAuthenticationMethodNTLM])
return YES;
// Explicitly reject ServerTrust. This is occasionally sent by IIS.
if([[protectionSpace authenticationMethod] isEqualToString:NSURLAuthenticationMethodServerTrust])
return NO;
return NO;
}
4- this was called properly
- (void)connection:(NSURLConnection*)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge*)challenge{
NSLog(#"didReceiveAuthenticationChallenge");
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodNTLM])
[[challenge sender] useCredential:[NSURLCredential
credentialWithUser:#"1234"
password:#"5678"
persistence:NSURLCredentialPersistenceNone] forAuthenticationChallenge:challenge];
}
4- this was called properly. From here, that's great because i know that the url was Unlock. So... how to play it with MPMoviePlayer?
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;{
NSLog(#"received response via nsurlconnection");
[self moviePlayerGO];
}
4- Stay black... :(
-(void)moviePlayerGO{
NSURL *movieURL = [NSURL URLWithString:#"http://www.abcd.com/_develop/video/01.mp4"];
//NSURL *movieURL = [NSURL URLWithString:#"http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"];
moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:movieURL];
moviePlayer.controlStyle = MPMovieControlStyleFullscreen;
moviePlayer.shouldAutoplay = YES;
[[moviePlayer view] setFrame: CGRectMake(0.0, 0.0, 350.0, 250.0)]; // 2X the native resolution
[self.view addSubview: [moviePlayer view]];
}

How to get HTML content of a website

In viewDidLoad, I'm using NSURLRequest and NSURLConnection:
NSURLRequest *site_request =
[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.google.com/"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
NSURLConnection *site_connection =
[[NSURLConnection alloc] initWithRequest:site_request delegate:self];
and then I use
-(void)connection:(NSURLConnection *)site_connection didReceiveData:(NSData *)data
{
site_response = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}
and I have the whole HTML in site_response.
I want to create an invisible UIWebView which will "open" the page from the NSURLRequest in order to use JavaScript to get content like this:
NSString *myText = [my_webView stringByEvaluatingJavaScriptFromString:
#"document.documentElement......"];
In my .h I have:
UIWebView *my_webview;
#property (nonatomic, retain) UIWebView *my_webview;
and in my .m I have:
#synthesize torrents_webview;
My viewDidLoad after NSURLRequest has
[my_webview loadRequest:site_request];
and I use
-(void)webViewDidFinishLoad:(UIWebView *)webView
{
//an alertview here
}
in order to be sure it works. But nothing happens. It doesn't give an alert view.
What am I doing wrong?
webViewDidFinishLoad: is a method of the UIWebView delegate. You are not setting the delegate anywhere in the code you have shown.
#interface YourClass : UIViewController <UIWebViewDelegate>
...
- (void)loadView
{
self.webView.delegate = self;
}
...
- (void)dealloc
{
self.webView.delegate = nil;
}
Also if you use NSURLRequest you're going to get the page again. But there's no need to use NSURLConnection, just go straight to loading the UIWebVIew using the NSURLRequest.
Or if you must use NSURLConnection then when the file has downloaded save it to disk and use LoadHTMLString to load the contents.
ViewController.h
#interface TopTorrents_ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource,UIWebViewDelegate>
{
UIWebView *torrents_webview;
}
#property (nonatomic, retain) UIWebView *torrents_webview;
ViewController.m
#synthesize torrents_webview;
- (void)viewDidLoad
{
torrents_webview.delegate = self;
NSURLRequest *site_request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.google.gr/"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0];
[torrents_webview loadRequest:site_request];
[super viewDidLoad];
}
-(void)webViewDidFinishLoad:(UIWebView *)webView
{
NSString *myText = [torrents_webview stringByEvaluatingJavaScriptFromString:#"document.getElementsByTagName('body')[0]"];
UIAlertView *my_alert = [[UIAlertView alloc] initWithTitle:#"mytitle" message:myText delegate:nil cancelButtonTitle:#"my button" otherButtonTitles:nil,nil];
[my_alert show];
}
this is my updated code... thanks

Resources