iOS開発-ライブビデオメディアでのギフト送信にNSOperationを使用
序文
- NSOperationは、ライブビデオなどでギフトを送信するために、iOS開発で使用する必要があります。
効果
開発前の準備
- ポッドのインポート
pod 'SDWebImage'
pod 'YYModel'
キーコード
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@class LDSGiftModel,LDSGiftShowView;
typedef void(^completeOpBlock)(BOOL finished,NSString *giftKey);
@interface LDSGiftOperation : NSOperation
+ (instancetype)addOperationWithView:(LDSGiftShowView *)giftShowView
OnView:(UIView *)backView
Info:(LDSGiftModel *)model
completeBlock:(completeOpBlock)completeBlock;
@property(nonatomic,strong) UIView *backView;
@property(nonatomic,strong) LDSGiftModel *model;
@property(nonatomic,copy) completeOpBlock opFinishedBlock;
@property(nonatomic,strong) LDSGiftShowView *giftShowView;
@end
#import "LDSGiftOperation.h"
#import "LDSGiftShowView.h"
#import "LDSGiftModel.h"
@implementation LDSGiftOperation
@synthesize finished = _finished;
@synthesize executing = _executing;
+ (instancetype)addOperationWithView:(LDSGiftShowView *)giftShowView
OnView:(UIView *)backView
Info:(LDSGiftModel *)model
completeBlock:(completeOpBlock)completeBlock {
LDSGiftOperation *op = [[LDSGiftOperation alloc] init];
op.giftShowView = giftShowView;
op.model = model;
op.backView = backView;
op.opFinishedBlock = completeBlock;
return op;
}
- (instancetype)init {
if (self = [super init]) {
_executing = NO;
_finished = NO;
}
return self;
}
- (void)start {
if ([self isCancelled]) {
_finished = YES;
return;
}
_executing = YES;
__weak typeof(self) weakSelf = self;
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
NSLog(@"currentThread - %@", [NSThread currentThread]);
[weakSelf.backView addSubview:weakSelf.giftShowView];
[weakSelf.giftShowView showGiftShowViewWithModel:weakSelf.model completeBlock:^(BOOL finished,NSString *giftKey) {
weakSelf.finished = finished;
if (weakSelf.opFinishedBlock) {
weakSelf.opFinishedBlock(finished,giftKey);
}
}];
}];
}
#pragma mark - 手动触发 KVO
- (void)setExecuting:(BOOL)executing {
[self willChangeValueForKey:@"isExecuting"];
_executing = executing;
[self didChangeValueForKey:@"isExecuting"];
}
- (void)setFinished:(BOOL)finished {
[self willChangeValueForKey:@"isFinished"];
_finished = finished;
[self didChangeValueForKey:@"isFinished"];
}
@end
デモ