Search code examples
objective-ccachingavplayer

Playing video from NSData in objective c


I have video's NSData and stored in my cache. I want to play this on AVPlayer (or some other player if iOS has) but not able to understand that in which format should I convert NSData so that it can be played on AVplayer. I don't want to save it locally and then give filepath's to AVplayer to play video. Kindly suggest is there any other way to play video from NSData.I have already spent 3 days on it but couldn't reach to any conclusion.Kindly give your suggestion.Any help or suggestion would be appreciated.Thanks in advance!


Solution

  • I give you the solution which gets the NSData from cache and plays the video.

    STEP 1:Add the AVKit framework in Target->BuilPhases->Link Binary With Libraries

    STEP 2:Then import in ViewController.Now it looks like below.

    ViewController.h

    #import <AVKit/AVKit.h>
    

    STEP 3:Declare the AVPlayerViewController as Strong in ViewController.h

    #import <UIKit/UIKit.h>
    #import <AVKit/AVKit.h>
    
    @interface ViewController : UIViewController
    @property (strong, nonatomic) AVPlayerViewController *playerViewController;
    - (IBAction)actionPlayVideo:(id)sender;
    
    @end
    

    STEP 4:Get the path from cache and convert to URL.Then finally play the video

    ViewController.m

    #import "ViewController.h"
    
    @interface ViewController (){
        NSURL *vedioURL;
    }
    
    @end
    
    @implementation ViewController
    @synthesize playerViewController;
    
    - (IBAction)actionPlayVideo:(id)sender{
        NSString *strNSDataPath = [[self getNSDataFromCache] stringByAppendingPathComponent:@"YourSavedNSDataName"];
        vedioURL =[NSURL fileURLWithPath:strNSDataPath];
        AVPlayerItem* playerItem = [AVPlayerItem playerItemWithURL:vedioURL];
        AVPlayer* playVideo = [[AVPlayer alloc] initWithPlayerItem:playerItem];
        playerViewController = [[AVPlayerViewController alloc] init];
        playerViewController.player = playVideo;
        playerViewController.player.volume = 0;
        playerViewController.view.frame = self.view.bounds;
        [self.view addSubview:playerViewController.view];
        [playVideo play];
    }
    -(NSString *)getNSDataFromCache{
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
        NSString *cachesDirectory = [paths objectAtIndex:0];
        return cachesDirectory;
    }