AVplayer 在 2-3 次后未显示在 ScrollView 中

发布于 2024-11-03 12:56:53 字数 155 浏览 5 评论 0原文


我在滚动视图中添加多个 AVPlayer 对象。第一次工作正常,但是当我返回到之前的视图并再次返回时,我无法在滚动视图中看到 AVPlayer 对象。

我需要多个 AVPlayer 的矩阵来显示我的视频的缩略图。

请尽快帮助我

提前致谢。

I am adding multiple AVPlayer objects in a scrollview. For the first time this is working fine but as i go back to my previous view and come back again i am not able to see AVPlayer objects in scrollView.

I need as matrix of multiple AVPlayer to show thumbnails of my videos.

Please help me asap

Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

江城子 2024-11-10 12:56:53

我遇到了类似的问题,经过大量搜索发现 AVPLayerItem 对象导致了这个问题。

基本上,当 AVPlayer 项目离开屏幕时,您需要确保所有内容都已正确释放,然后当它们返回屏幕时重新创建所有内容。

作为发布过程的一部分,请添加以下行:

[AVPlayer replaceCurrentItemWithPlayerItem:nil];

That sorted a veryimilar issues for me.

I had a similar problem and after a lot of searching discovered that the AVPLayerItem object causes this issue.

Basically when the AVPlayer items go offscreen you need to make sure everything is released properly, and then recreate everything when they come back on screen.

As part of the release process, include the line:

[AVPlayer replaceCurrentItemWithPlayerItem:nil];

That sorted a very similar issue for me.

半透明的墙 2024-11-10 12:56:53
[AVPlayer replaceCurrentItemWithPlayerItem:nil];

也解决了我无法立即释放当前播放器项目的问题。 (无法手动执行此操作,因为它由班级保留..)

[AVPlayer replaceCurrentItemWithPlayerItem:nil];

also solves my problem of cannot releasing current player item immediately. (can't manually do that because it's retained by the class..)

橘寄 2024-11-10 12:56:53

以下是如何让 10 个 AVPlayer 在同一个滚动视图内同时播放,每次滚动时:

//
//  ViewController.m
//  VideoWall
//
//  Created by James Alan Bush on 6/13/16.
//  Copyright © 2016 James Alan Bush. All rights reserved.
//

#import "ViewController.h"
#import "AppDelegate.h"

static NSString *kCellIdentifier = @"Cell Identifier";

@interface ViewController () {
    dispatch_queue_t dispatchQueueLocal;
}

@end

@implementation ViewController

- (id)initWithCollectionViewLayout:(UICollectionViewFlowLayout *)layout
{
    if (self = [super initWithCollectionViewLayout:layout])
    {
        [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:kCellIdentifier];
        dispatchQueueLocal = dispatch_queue_create( "local session queue", DISPATCH_QUEUE_CONCURRENT );
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self.collectionView setDataSource:self];
    [self.collectionView setContentSize:CGSizeMake(AppDelegate.sharedAppDelegate.width, AppDelegate.sharedAppDelegate.height)];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)dealloc {
    [super dealloc];
}

#pragma mark <UICollectionViewDataSource>

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

#pragma mark - UICollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return AppDelegate.sharedAppDelegate.assetsFetchResults.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    UICollectionViewCell *cell = (UICollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:kCellIdentifier forIndexPath:indexPath];
    [CATransaction begin];
    [CATransaction setCompletionBlock:^{
        cell.contentView.layer.sublayers = nil;
        dispatch_release(dispatchQueueLocal);
    }];
    dispatch_retain(dispatchQueueLocal);
    dispatch_async( dispatchQueueLocal, ^{
        [self drawPlayerLayerForCell:cell atIndexPath:indexPath];
    });
    [CATransaction commit];

    return cell;
}

- (void)drawPlayerLayerForCell:(UICollectionViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    void (^drawPlayerLayer)(UICollectionViewCell*, NSIndexPath*) = ^(UICollectionViewCell* cell, NSIndexPath* indexPath) {
        [AppDelegate.sharedAppDelegate.imageManager requestPlayerItemForVideo:AppDelegate.sharedAppDelegate.assetsFetchResults[indexPath.item] options:nil resultHandler:^(AVPlayerItem * _Nullable playerItem, NSDictionary * _Nullable info) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if(![[info objectForKey:PHImageResultIsInCloudKey] boolValue]) {
                    AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:[AVPlayer playerWithPlayerItem:playerItem]];
                    [playerLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
                    [playerLayer setBorderColor:[UIColor whiteColor].CGColor];
                    [playerLayer setBorderWidth:1.0f];
                    [playerLayer setFrame:cell.contentView.bounds];

                    [cell.contentView.layer addSublayer:playerLayer];
                    [(AVPlayer *)playerLayer.player play];

                } else {
                    [AppDelegate.sharedAppDelegate.imageManager requestImageForAsset:AppDelegate.sharedAppDelegate.assetsFetchResults[indexPath.item]
                                                                          targetSize:CGSizeMake(AppDelegate.sharedAppDelegate.flowLayout.itemSize.width, AppDelegate.sharedAppDelegate.flowLayout.itemSize.height)
                                                                         contentMode:PHImageContentModeAspectFill
                                                                             options:nil
                                                                       resultHandler:^(UIImage *result, NSDictionary *info) {
                                                                           dispatch_async(dispatch_get_main_queue(), ^{
                                                                               cell.contentView.layer.contents = (__bridge id)result.CGImage;
                                                                           });
                                                                       }];
                }
            });
        }];
    };
    drawPlayerLayer(cell, indexPath);
}

@end

这是 AppDelegate 实现文件:

//
//  AppDelegate.m
//  VideoWall
//
//  Created by James Alan Bush on 6/13/16.
//  Copyright © 2016 James Alan Bush. All rights reserved.
//

#import "AppDelegate.h"
#import "ViewController.h"

@implementation AppDelegate

+ (AppDelegate *)sharedAppDelegate
{
    return (AppDelegate *)[[UIApplication sharedApplication] delegate];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch

    self.width = [[UIScreen mainScreen] bounds].size.width / 2.0;
    self.height = [[UIScreen mainScreen] bounds].size.height / 4.0;

    self.window                    = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.rootViewController = [self viewController];
    self.window.rootViewController.view = self.viewController.view;


    [self.window makeKeyAndVisible];

    return YES;
}

- (ViewController *)viewController {
    ViewController *c = self->_viewController;
    if (!c) {
        c = [[ViewController alloc] initWithCollectionViewLayout:[self flowLayout]];
        [c.view setFrame:[[UIScreen mainScreen] bounds]];
        self->_viewController = c;
    }
    return c;
}

- (UICollectionViewFlowLayout *)flowLayout {
    UICollectionViewFlowLayout *v = self->_flowLayout;
    if (!v) {
        v = [UICollectionViewFlowLayout new];
        [v setItemSize:CGSizeMake(AppDelegate.sharedAppDelegate.width, AppDelegate.sharedAppDelegate.height)];
        [v setSectionInset:UIEdgeInsetsMake(0.0, 0.0, 0.0, 0.0)];
        [v setMinimumLineSpacing:0.0];
        [v setMinimumInteritemSpacing:0.0];
        [v setEstimatedItemSize:CGSizeMake(AppDelegate.sharedAppDelegate.width, AppDelegate.sharedAppDelegate.height)];
        self->_flowLayout = v;
    }
    return v;
}

- (PHCachingImageManager *)imageManager {
    PHCachingImageManager *i = self->_imageManager;
    if (!i) {
        i = [[PHCachingImageManager alloc] init];
        self->_imageManager = i;
    }
    return i;
}

- (PHFetchResult *)assetsFetchResults {
    PHFetchResult *i = self->_assetsFetchResults;
    if (!i) {
        PHFetchResult *smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeSmartAlbumVideos options:nil];
        PHAssetCollection *collection = smartAlbums.firstObject;
        if (![collection isKindOfClass:[PHAssetCollection class]])
            return nil;
        PHFetchOptions *allPhotosOptions = [[PHFetchOptions alloc] init];
        allPhotosOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO]];
        i = [PHAsset fetchAssetsInAssetCollection:collection options:allPhotosOptions];
        self->_assetsFetchResults = i;
    }
    return i;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end

这是您唯一需要的两个文件;没有 NIB/XIB。

Here's how you get 10 AVPlayers to play simultaneously, inside the same scrollView, each and every time you scroll it:

//
//  ViewController.m
//  VideoWall
//
//  Created by James Alan Bush on 6/13/16.
//  Copyright © 2016 James Alan Bush. All rights reserved.
//

#import "ViewController.h"
#import "AppDelegate.h"

static NSString *kCellIdentifier = @"Cell Identifier";

@interface ViewController () {
    dispatch_queue_t dispatchQueueLocal;
}

@end

@implementation ViewController

- (id)initWithCollectionViewLayout:(UICollectionViewFlowLayout *)layout
{
    if (self = [super initWithCollectionViewLayout:layout])
    {
        [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:kCellIdentifier];
        dispatchQueueLocal = dispatch_queue_create( "local session queue", DISPATCH_QUEUE_CONCURRENT );
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self.collectionView setDataSource:self];
    [self.collectionView setContentSize:CGSizeMake(AppDelegate.sharedAppDelegate.width, AppDelegate.sharedAppDelegate.height)];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)dealloc {
    [super dealloc];
}

#pragma mark <UICollectionViewDataSource>

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

#pragma mark - UICollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return AppDelegate.sharedAppDelegate.assetsFetchResults.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    UICollectionViewCell *cell = (UICollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:kCellIdentifier forIndexPath:indexPath];
    [CATransaction begin];
    [CATransaction setCompletionBlock:^{
        cell.contentView.layer.sublayers = nil;
        dispatch_release(dispatchQueueLocal);
    }];
    dispatch_retain(dispatchQueueLocal);
    dispatch_async( dispatchQueueLocal, ^{
        [self drawPlayerLayerForCell:cell atIndexPath:indexPath];
    });
    [CATransaction commit];

    return cell;
}

- (void)drawPlayerLayerForCell:(UICollectionViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    void (^drawPlayerLayer)(UICollectionViewCell*, NSIndexPath*) = ^(UICollectionViewCell* cell, NSIndexPath* indexPath) {
        [AppDelegate.sharedAppDelegate.imageManager requestPlayerItemForVideo:AppDelegate.sharedAppDelegate.assetsFetchResults[indexPath.item] options:nil resultHandler:^(AVPlayerItem * _Nullable playerItem, NSDictionary * _Nullable info) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if(![[info objectForKey:PHImageResultIsInCloudKey] boolValue]) {
                    AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:[AVPlayer playerWithPlayerItem:playerItem]];
                    [playerLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
                    [playerLayer setBorderColor:[UIColor whiteColor].CGColor];
                    [playerLayer setBorderWidth:1.0f];
                    [playerLayer setFrame:cell.contentView.bounds];

                    [cell.contentView.layer addSublayer:playerLayer];
                    [(AVPlayer *)playerLayer.player play];

                } else {
                    [AppDelegate.sharedAppDelegate.imageManager requestImageForAsset:AppDelegate.sharedAppDelegate.assetsFetchResults[indexPath.item]
                                                                          targetSize:CGSizeMake(AppDelegate.sharedAppDelegate.flowLayout.itemSize.width, AppDelegate.sharedAppDelegate.flowLayout.itemSize.height)
                                                                         contentMode:PHImageContentModeAspectFill
                                                                             options:nil
                                                                       resultHandler:^(UIImage *result, NSDictionary *info) {
                                                                           dispatch_async(dispatch_get_main_queue(), ^{
                                                                               cell.contentView.layer.contents = (__bridge id)result.CGImage;
                                                                           });
                                                                       }];
                }
            });
        }];
    };
    drawPlayerLayer(cell, indexPath);
}

@end

Here's the AppDelegate implementation file:

//
//  AppDelegate.m
//  VideoWall
//
//  Created by James Alan Bush on 6/13/16.
//  Copyright © 2016 James Alan Bush. All rights reserved.
//

#import "AppDelegate.h"
#import "ViewController.h"

@implementation AppDelegate

+ (AppDelegate *)sharedAppDelegate
{
    return (AppDelegate *)[[UIApplication sharedApplication] delegate];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch

    self.width = [[UIScreen mainScreen] bounds].size.width / 2.0;
    self.height = [[UIScreen mainScreen] bounds].size.height / 4.0;

    self.window                    = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.rootViewController = [self viewController];
    self.window.rootViewController.view = self.viewController.view;


    [self.window makeKeyAndVisible];

    return YES;
}

- (ViewController *)viewController {
    ViewController *c = self->_viewController;
    if (!c) {
        c = [[ViewController alloc] initWithCollectionViewLayout:[self flowLayout]];
        [c.view setFrame:[[UIScreen mainScreen] bounds]];
        self->_viewController = c;
    }
    return c;
}

- (UICollectionViewFlowLayout *)flowLayout {
    UICollectionViewFlowLayout *v = self->_flowLayout;
    if (!v) {
        v = [UICollectionViewFlowLayout new];
        [v setItemSize:CGSizeMake(AppDelegate.sharedAppDelegate.width, AppDelegate.sharedAppDelegate.height)];
        [v setSectionInset:UIEdgeInsetsMake(0.0, 0.0, 0.0, 0.0)];
        [v setMinimumLineSpacing:0.0];
        [v setMinimumInteritemSpacing:0.0];
        [v setEstimatedItemSize:CGSizeMake(AppDelegate.sharedAppDelegate.width, AppDelegate.sharedAppDelegate.height)];
        self->_flowLayout = v;
    }
    return v;
}

- (PHCachingImageManager *)imageManager {
    PHCachingImageManager *i = self->_imageManager;
    if (!i) {
        i = [[PHCachingImageManager alloc] init];
        self->_imageManager = i;
    }
    return i;
}

- (PHFetchResult *)assetsFetchResults {
    PHFetchResult *i = self->_assetsFetchResults;
    if (!i) {
        PHFetchResult *smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeSmartAlbumVideos options:nil];
        PHAssetCollection *collection = smartAlbums.firstObject;
        if (![collection isKindOfClass:[PHAssetCollection class]])
            return nil;
        PHFetchOptions *allPhotosOptions = [[PHFetchOptions alloc] init];
        allPhotosOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO]];
        i = [PHAsset fetchAssetsInAssetCollection:collection options:allPhotosOptions];
        self->_assetsFetchResults = i;
    }
    return i;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end

These are the only two files you need; no NIB/XIB.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文