iOS13 执行内购的代理方法时的注意点

最近在做苹果内购,内购有如下代理方法
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response API_AVAILABLE(ios(3.0), macos(10.7), watchos(6.2));
该代理方法是在当收到内购产品的响应信息时候就会调用。

  • 注意了,注意了,实现该代理方法时,通过[NSThread currentThread]打印当前线程可知,该代理方法中的代码都是在子线程中执行的。我们都知道,在子线程是不能更新ui的,必须在主线程中更新UI。因此你想在该代理方法中更新ui(例如弹框...)的话,必须回到主线程中,否则就会报如下错误`

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Modifications to the layout engine must not be performed from a background thread after it has been accessed from the main thread.'


错误做法

- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response{
        NSLog(@"当前线程%@",[NSThread currentThread]);// NSThread: 0x282d7c980>{number = 13, name = (null)}
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"结果" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
        UIAlertAction *actionCancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"点击了取消");
        }];
        
        UIAlertAction *actionOK = [UIAlertAction actionWithTitle:@"确定退出" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"点击了确定");
            [self.navigationController popViewControllerAnimated:YES];
        }];
        [alertController addAction:actionCancel];
        [alertController addAction:actionOK];
        
        [self presentViewController:alertController animated:YES completion:nil];
}

正确做法

- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response{
    NSLog(@"当前线程%@",[NSThread currentThread]);// NSThread: 0x282d7c980>{number = 13, name = (null)}
    dispatch_async(dispatch_get_main_queue(), ^{
         NSLog(@"此时当前线程%@",[NSThread currentThread]);// <NSThread: 0x283253080>{number = 1, name = main}
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"结果" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
        UIAlertAction *actionCancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"点击了取消");
        }];
        
        UIAlertAction *actionOK = [UIAlertAction actionWithTitle:@"确定退出" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"点击了确定");
            [self.navigationController popViewControllerAnimated:YES];
        }];
        [alertController addAction:actionCancel];
        [alertController addAction:actionOK];
        
        [self presentViewController:alertController animated:YES completion:nil];
        
    });    
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容