How play a .tmp file with MPMoviePlayerController in objective-c - objective-c

I download a video file .mp4 from server with NSURLSessionDownloadTask but in the delegate didFinishDownloadingToURL:(NSURL *)location, location is a .tmp file like this
file:///private/var/mobile/Applications/BEA4F9F8-D685-468F-B96C-AE7890ACFC5E/tmp/CFNetworkDownload_LQuGoo.tmp
When I try to initialize MPMoviePlayerController console show this error
_itemFailedToPlayToEnd: { kind = 1;new = 2; old = 0;} and screen show black
I researched and I can save the .tmp file and play .mp4 from my directory but I don't want to do that, I want to know if there is a way to play directly with MPMoviePlayerController. My code
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
config.HTTPMaximumConnectionsPerHost = 1;
NSURLSession *downloadSession = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
NSURLSessionDownloadTask * downloadTask =[downloadSession downloadTaskWithURL:self.userRecord.URL completionHandler:nil];
[downloadTask resume];
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
self.userRecord.locationData = location;
[(NSObject *)self.delegate performSelectorOnMainThread:#selector(fileDownloaderDidFinish:) withObject:self waitUntilDone:NO];
return;
}
-(void)fileDownloaderDidFinish:(FileDownloader *)fileDownloader {
[self setVideoPlayer:[[MPMoviePlayerController alloc] initWithContentURL:fileDownloader.userRecord.locationData]]
;
[self.videoPlayer setControlStyle:MPMovieControlStyleNone];
[self.videoPlayer.view setFrame:CGRectMake(0, 0, 320, 320)];
[self.videoPlayer prepareToPlay];
[self.vwContainerVideo addSubview:self.videoPlayer.view];
[self.vwContainerVideo bringSubviewToFront:self.videoPlayer.view];
[self.vwContainerVideo bringSubviewToFront:self.btPlay];
[self.vwContainerVideo bringSubviewToFront:self.imPlay];
[self.vwContainerThumbnail setHidden:YES];
[AnimationHelper fadeIn:self.vwContainerVideo withDuration:0.5 andWait:0.5];
[self.vwContainerVideo setHidden:NO];
[self.videoPlayer play];
}

My decision was to save file .tmp in a directory and init MPMoviePlayerController with the url from directory.
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
config.HTTPMaximumConnectionsPerHost = 1;
NSURLSession *downloadSession = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
NSURLSessionDownloadTask * downloadTask =[downloadSession downloadTaskWithURL:self.userRecord.URL completionHandler:nil];
[downloadTask resume];
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
self.userRecord.data = [NSData dataWithContentsOfURL:location];
[self.userRecord.data writeToFile:[rootDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#/%#.%#",self.userRecord.directory,self.userRecord.nameFile, self.userRecord.ext]] options:NSDataWritingWithoutOverwriting error:&error];
self.userRecord.locationData = [NSURL fileURLWithPath:[rootDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#/%#.%#",self.userRecord.directory,self.userRecord.nameFile, self.userRecord.ext]]];
[(NSObject *)self.delegate performSelectorOnMainThread:#selector(fileDownloaderDidFinish:) withObject:self waitUntilDone:NO];
return;
}
-(void)fileDownloaderDidFinish:(FileDownloader *)fileDownloader {
[self setVideoPlayer:[[MPMoviePlayerController alloc] initWithContentURL:fileDownloader.userRecord.locationData]]
;
[self.videoPlayer setControlStyle:MPMovieControlStyleNone];
[self.videoPlayer.view setFrame:CGRectMake(0, 0, 320, 320)];
[self.videoPlayer prepareToPlay];
[self.vwContainerVideo addSubview:self.videoPlayer.view];
[self.vwContainerVideo bringSubviewToFront:self.videoPlayer.view];
[self.vwContainerVideo bringSubviewToFront:self.btPlay];
[self.vwContainerVideo bringSubviewToFront:self.imPlay];
[self.vwContainerThumbnail setHidden:YES];
[AnimationHelper fadeIn:self.vwContainerVideo withDuration:0.5 andWait:0.5];
[self.vwContainerVideo setHidden:NO];
[self.videoPlayer play];
}

Related

How to open a youtube private link

NSURL *url=[NSURL URLWithString:#"https://m.youtube.com/watch?v=E9wVJJhDOYQ&t=0s"];
NSLog(#"url is %#", url);
MPMoviePlayerController * _moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:url];
[[_moviePlayer view]setFrame:CGRectMake(50, 100, 200, 200)];
[_moviePlayer setFullscreen:NO animated:YES];
_moviePlayer.scalingMode = MPMovieScalingModeAspectFit;
_moviePlayer.shouldAutoplay= YES;
[[self view] addSubview: [_moviePlayer view]];

Video is not playing in ios8 using AVPlayer

Video stored in documents directory is not playing if i run app in ios8 but works perfect if i run in ios7
I am downloading video in documents directory using AFNetworking.Here is the code.
NSURLRequest *request = [NSURLRequest requestWithURL:urlVideo];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
NSString *path = [dataPath stringByAppendingPathComponent:[urlVideo lastPathComponent]];
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
self.isDownloadingComplete = YES;
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Video Downloading Failed");
}];
[operation start];
And i am playing that downloaded video using AVPlayer. Here is the code.
NSURL* playbackURL = [[NSURL alloc] initFileURLWithPath:strPath isDirectory:NO];
[[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:[_pl currentItem]];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(playerItemDidReachEnd:)
name:AVPlayerItemDidPlayToEndTimeNotification
object:[_pl currentItem]];
AVAsset *asset = [AVURLAsset URLAssetWithURL:playbackURL options:nil];
AVPlayerItem *anItem = [AVPlayerItem playerItemWithAsset:asset];
_pl = [AVPlayer playerWithPlayerItem:anItem];
_pl.volume = 1.0;
_pl.actionAtItemEnd = AVPlayerActionAtItemEndNone;
AVPlayerLayer *layer = [AVPlayerLayer playerLayerWithPlayer:_pl];
layer.videoGravity = AVLayerVideoGravityResizeAspectFill;
layer.frame = CGRectMake(0, 0, 305, 306);
[self.contentView.layer addSublayer: layer];
[_pl play];
I think issue is with Documents Directory as i run the app, the document path is changing every time, but i am sending correct path every time. Here is reference: http://pinkstone.co.uk/where-is-the-documents-directory-for-the-ios-8-simulator/
I finally solved it by following code
I just replaced
[self.contentView.layer addSublayer: layer];
with
[self.layer addSublayer:layer];
And it is working fine, but still i am not getting what is the problem with [self.contentView.layer addSublayer: layer];
Let me know if anyone have strong proof.
Thanks

How do I dismiss a UIView after scanning a barcode?

I have an iPad app that I want to add a barcode reader to... this is the code for the initialization of the barcoder code:
-(void) scanInitializationCode {
_highlightView = [[UIView alloc] init];
_highlightView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleBottomMargin;
_highlightView.layer.borderColor = [UIColor greenColor].CGColor;
_highlightView.layer.borderWidth = 3;
[self.view addSubview:_highlightView];
// define the label to display the results of the scan
_label = [[UILabel alloc] init];
_label.frame = CGRectMake(0, self.view.bounds.size.height - 40, self.view.bounds.size.width, 40);
_label.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
_label.backgroundColor = [UIColor colorWithWhite:0.15 alpha:0.65];
_label.textColor = [UIColor whiteColor];
_label.textAlignment = NSTextAlignmentCenter;
_label.text = #"(none)";
[self.view addSubview:_label];
// session initialization
_session = [[AVCaptureSession alloc] init];
_device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
NSError *error = nil;
// define the input device
_input = [AVCaptureDeviceInput deviceInputWithDevice:_device error:&error];
if (_input) {
[_session addInput:_input];
} else {
NSLog(#"Error: %#", error);
}
// and output device
_output = [[AVCaptureMetadataOutput alloc] init];
[_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
[_session addOutput:_output];
_output.metadataObjectTypes = [_output availableMetadataObjectTypes];
// and preview layer
_prevLayer = [AVCaptureVideoPreviewLayer layerWithSession:_session];
_prevLayer.frame = self.view.bounds;
_prevLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
[self.view.layer addSublayer:_prevLayer];
}
This is the AVCaptureMetadataOutputObjectsDelegate code:
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
CGRect highlightViewRect = CGRectZero;
AVMetadataMachineReadableCodeObject *barCodeObject;
NSString *detectionString = nil;
NSArray *barCodeTypes = #[AVMetadataObjectTypeEAN13Code];
for (AVMetadataObject *metadata in metadataObjects) {
for (NSString *type in barCodeTypes) {
if ([metadata.type isEqualToString:type])
{
barCodeObject = (AVMetadataMachineReadableCodeObject *)[_prevLayer transformedMetadataObjectForMetadataObject:(AVMetadataMachineReadableCodeObject *)metadata];
highlightViewRect = barCodeObject.bounds;
detectionString = [(AVMetadataMachineReadableCodeObject *)metadata stringValue];
break;
}
}
if (detectionString != nil) {
_label.text = detectionString;
oISBNField.text = detectionString; // move detectionString to ISBN textbox
[_session stopRunning];
[_highlightView removeFromSuperview];
break;
}
else
_label.text = #"(none)";
}
This is the code that starts the scanning process by having the user tap a UIButton:
- (IBAction)aReadBarcode:(UIButton *)sender {
[self scanInitializationCode];
[_session startRunning];
// display the activity
[self.view bringSubviewToFront:_highlightView];
[self.view bringSubviewToFront:_label];
oISBNField.text = scanResults;
}
The problem is that once the scan has found the barcode, it stays visible; what I want to do is have it return to the UIView that has the button that caused it to start scanning (in other words, I want the _highlightView to disappear). I have tried all kinds of "dismissal" methods, even putting it at the back of the z-order, but none of them work. How can I make the highlightView disappear from the screen?
The answer:
[_prevLayer removeFromSuperlayer]; after [_session stopRunning]

MPMoviePlayerController does not work in ios 5

i have a problem while working with MPMoviePlayerController. It doesnot work in ios 5 just a black screen to show. Not even throws any exception or any error.
Here is my code:
NSString *path = [[NSBundle mainBundle] pathForResource:#"cavity" ofType:#"mov"];
NSLog(#"%#",path);
_movieController = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL URLWithString:path]];
[_movieController prepareToPlay];
[_movieController setFullscreen:NO];
[_movieController.view setFrame:CGRectMake(10, 25, 287, 213)];
[_movieController setControlStyle:MPMovieControlStyleEmbedded];
[_movieView addSubview:_movieController.view];
[_movieController play];
The _movieController object has been declared in .h file but still not in working condition.
try this
MPMoviePlayerViewController *mp = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL URLWithString:url]];
[[mp moviePlayer] prepareToPlay];
[[mp moviePlayer] setUseApplicationAudioSession:NO];
[[mp moviePlayer] setShouldAutoplay:YES];
[[mp moviePlayer] setControlStyle:2];
[[mp moviePlayer] setRepeatMode:MPMovieRepeatModeOne];
[self presentMoviePlayerViewControllerAnimated:mp];

Objective-c Changing UIImagePickerController to video mode

I have an application which I want onlt to show in the background the video source from the camera. I have the following code in my viewcontroller:
#if !TARGET_IPHONE_SIMULATOR
imagePickerController = [[UIImagePickerController alloc] initWithRootViewController:self];
imagePickerController.delegate = self;
imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
imagePickerController.navigationBarHidden = YES;
imagePickerController.toolbarHidden = NO;
imagePickerController.showsCameraControls = NO;
//...
[self.view addSubview:self.imagePickerController.view];
[imagePickerController viewWillAppear:YES];
[imagePickerController viewDidAppear:YES];
#endif
//...
[self.view addSubview:otherthings];
Then I add other views on top and I have sounds too. However I changed the imagepicker mode to video but it freezes when a sound plays. here's what i changed:
#if !TARGET_IPHONE_SIMULATOR
imagePickerController = [[UIImagePickerController alloc] init];//initWithRootViewController:self];
imagePickerController.delegate = self;
imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
NSArray *mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
NSArray *videoMediaTypesOnly = [mediaTypes filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"(SELF contains %#)", #"movie"]];
BOOL movieOutputPossible = (videoMediaTypesOnly != nil);
if (movieOutputPossible) {
imagePickerController.mediaTypes = videoMediaTypesOnly;
imagePickerController.videoQuality = UIImagePickerControllerQualityTypeHigh;
imagePickerController.navigationBarHidden = YES;
imagePickerController.toolbarHidden = YES;
imagePickerController.showsCameraControls = NO;
}
#endif
Anyone knows why the camera pickers freezes when a sound plays? The sound is an AVAudioPlayer by the way.
Solution: Use AVFOundation instead of UIImagePickerController.
videoBackground = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 480.0)];
AVCaptureSession *session = [[AVCaptureSession alloc] init];
session.sessionPreset = AVCaptureSessionPresetMedium;
CALayer *viewLayer = videoBackground.layer;
NSLog(#"viewLayer = %#", viewLayer);
AVCaptureVideoPreviewLayer *captureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];
captureVideoPreviewLayer.frame = videoBackground.bounds;
[videoBackground.layer addSublayer:captureVideoPreviewLayer];
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
NSError *error = nil;
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
if (!input) {
// Handle the error appropriately.
NSLog(#"ERROR: trying to open camera: %#", error);
}
[session addInput:input];
[session startRunning];
[self.view addSubview:videoBackground];