您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發基礎

如何優雅地往 Feeds 流裡插入廣告——代碼實踐篇

編輯:iOS 開發基礎

應用發展到一定階段,幾乎都會選擇在 feeds 流中插入廣告來做變現,這是每個產品都要走的流程。微信朋友圈、微博、QQ 空間都是如此,凡是帶 feeds 流的產品基本都逃不開這件事。

如果現在要在你已有的業務列表裡插入廣告,你會怎麼做?很多人的第一反應是:讓接口把廣告和業務數據合並後一起下發,然後在業務層寫各種 if 判斷。

走過這條路的人都懂有多累。這種插入方式意味著你要到處改代碼,而且很容易在某個不起眼的角落踩坑——比如某處直接調用了:

- (nullable __kindof UITableViewCell *)cellForRowAtIndexPath:(NSIndexPath *)indexPath;

而返回的類型和你預期的不一致,應用當場 Crash。

換個思路

現在有一個框架專門解決這種場景。它的核心思路是面向切面(AOP):不侵入業務代碼,把廣告邏輯掛到 UITableView 的數據流上去。目前公司多款應用已經接入,總用戶量突破 1 億,日活約 700 萬,穩定性還是值得信賴的(有問題歡迎提 issue)。

要達到的目標:

1. 舊代碼盡量少改,甚至不改。

2. 業務模塊與廣告模塊徹底分離。

3. 廣告模塊能拿到真實的數據源。

4. 上手足夠簡單。

用法

我拉了 YYKit 下來做驗證。喜歡這個庫,很大一部分原因是它自帶 Feeds(Twitter、微博)的 demo,業務邏輯夠真實、夠複雜,正好用來試刀。

開始

我原本並不熟悉這個 demo 的內部實現,但有了 IMYAOPTableView,我不需要看懂它,也能完成廣告插入。

找到初始化 Twitter / 微博 的那個 ViewController,拿到 TableView 的 AopUtils,只需要 3 行代碼,外加一個屬性聲明。

/// 只是聲明,防止提前釋放
@property (nonatomic, strong) IMYAOPDemo* aopDemo;

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *className = self.classNames[indexPath.row];
    Class class = NSClassFromString(className);
    if (class) {
        UIViewController *ctrl = class.new;

        /// begin 插入 3 行代碼
        self.aopDemo = [IMYAOPDemo new];
        UITableView* feedsTableView = [ctrl valueForKey:@"tableView"];
        self.aopDemo.aopUtils = feedsTableView.aop_utils;
        /// end

        ctrl.title = _titles[indexPath.row];
        self.title = @" ";
        [self.navigationController pushViewController:ctrl animated:YES];
    }
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
}

接著新建一個類來承載廣告邏輯,這裡簡單建了個 IMYAOPDemo。核心就兩件事:設置數據回調,以及指定插入位置。

- (void)injectTableView {
    [self.aopUtils.tableView registerClass:[UITableViewCell class]
                    forCellReuseIdentifier:@"AD"];
    /// 廣告回調,跟 TableView 的 Delegate、DataSource 一樣
    self.aopUtils.delegate = self;
    self.aopUtils.dataSource = self;

    dispatch_async(dispatch_get_main_queue(), ^{
        [self insertRows];
    });
}

/// 簡單的 rows 插入
- (void)insertRows {
    NSMutableArray* insertBodys = [NSMutableArray array];
    /// 隨機生成了 5 個要插入的位置
    for (int i = 0; i < 5; i++) {
        NSIndexPath* indexPath = [NSIndexPath indexPathForRow:arc4random() inSection:0];
        [insertBodys addObject:[IMYAOPTableViewInsertBody insertBodyWithIndexPath:indexPath]];
    }
    /// 清空舊數據
    [self.aopUtils insertWithSections:nil];
    [self.aopUtils insertWithIndexPaths:nil];

    /// 插入新數據,同一個 row 會按數組順序遞增
    [self.aopUtils insertWithIndexPaths:insertBodys];
    /// 調用 tableView 的 reloadData,進行頁面刷新
    [self.aopUtils.tableView reloadData];
}

廣告回調這部分,看協議聲明就明白了——它同樣繼承了 TableView 的 Delegate 和 DataSource,保持與原生回調一致,方便把已有的廣告代碼平滑遷移過來。

@protocol IMYAOPTableViewDelegate;
@protocol IMYAOPTableViewDataSource

接下來實現具體的廣告回調。下面這兩個方法其實不會被調用——數據源數量由業務模塊決定——但如果不實現,Xcode 會報警告,所以順手寫上。

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"AD"];
    if (cell.contentView.subviews.count == 0) {
        CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
        CGFloat imageHeight = 162 * (screenWidth / 320.0f);
        UIImageView* imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, screenWidth, imageHeight)];
        imageView.image = [UIImage imageNamed:@"aop_ad_image.jpeg"];
        imageView.layer.borderColor = [UIColor blackColor].CGColor;
        imageView.layer.borderWidth = 1;
        [cell.contentView addSubview:imageView];

        UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(200, 100, 200, 50)];
        label.text = @"不要臉的廣告!";
        [cell.contentView addSubview:label];
    }
    return cell;
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"插入的 cell 要顯示啦");
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"被點擊了><"
        message:[NSString stringWithFormat:@"我的位置: %@", indexPath]
        delegate:nil cancelButtonTitle:@"哦~滾" otherButtonTitles:nil];
    [alertView show];
}

效果圖是個 gif,如果不會動,可以去 git 倉庫的 readme 看:

有興趣的話,可以再看看具體源碼實現。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved