I have read several posts here about live streaming video/audio
. Unfortunately it seems that there is not any "good" solution.
I want same functionality for video which is provided SDWebImageView
for images.
Right now, I am using following code:-
NSURL *url=[[NSURL alloc] initWithString:@"http://www.ebookfrenzy.com/ios_book/movie/movie.mov"];
MPMoviePlayerController *moviePlayer=[[MPMoviePlayerController alloc] initWithContentURL:url];
moviePlayer.controlStyle=MPMovieControlStyleDefault;
moviePlayer.shouldAutoplay=YES;
But when I scrolled tableview
, all videos download again and again. So How can I stop that downloading?
Is there any better solution for playing video into UITableView
? Same Facebook, Instagram, and Vine Apps doing?
When you scroll table view then method
-tableView:cellForRowAtIndexPath:
is fired (actually every time when cell will be visible this method is called). I believe that you are allocating and initializing yours MediaPlayer in this method and that's why video is downloaded again. You could try to add array and store already created cells in it (some kind of cache). Then your-tableView:cellForRowAtIndexPath
should check if it has sth cached for actual index. If yes then show cached cell. If no then it should create cell, alloc, and init player and then store cell in cache.My ViewController has property:
NSMutableDictionary *cache;
and inViewDidLoad
I have:cache = [[NSMutableDictionary alloc] init];
My-tableView:cellForRowAtIndexPath:
looks like this:It works for me. Of course you need to use your own datasource etc.
Don't use
MPMoviePlayerController
, useAVFoundation
'sAVPlayer
.Additionally, don't couple the downloading of your asset to your
UITableViewCell
subclass. Use an additional data source to download and manage the video assets.There are a few ways you can do this.
Keep a data source array of
AVPlayerItem
objects initialized by URL. Instead of loading the asset each time you scroll to a cell, just load theAVPlayerItem
into the cell's player, and remove it when you scroll away.If you need to persist the video data, consider downloading each video to a temporary file in your Documents directory. When the file has finished downloading, load that data into an
AVAsset
using itsinitWithURL:
method and point the URL to your local file. When ready, you can load your asset into anAVPlayerItem
usinginitWithAsset:
and play the video.Swift 3