【问题标题】:iOS: UIBackgroundFetchResult completion handler inside of blockiOS:块内的 UIBackgroundFetchResult 完成处理程序
【发布时间】:2015-04-06 00:13:53
【问题描述】:

在这里可以使用一点帮助,因为我对块和完成处理程序的理解非常有限。

我正在尝试在 iOS 中实现后台获取,同时遵循本教程并根据需要进行更改:http://www.appcoda.com/ios7-background-fetch-programming/

我已经实现了启用后台获取所需的前导,并在我的 viewController 中实现了以下方法,并验证了它在模拟后台获取时被触发:

- (void)retrieveMessagesInBackgroundWithHandler:(void (^)(UIBackgroundFetchResult))completionHandler

在我的方法内部,我正在调用一个类 SoapRequest 来执行对 Web 服务的异步调用,并且该完成处理程序我能够确定我是否有新数据。最终,我想发回 UIBackgroundFetchResult 值:

SoapRequest *sr = [SoapRequest createWithURL:[NSURL URLWithString:kServiceURL] soapAction:soapAction postData:soapEnvelope deserializeTo:[NSMutableArray array] completionBlock:^(BOOL succeeded, id output, SoapFault *fault, NSError *error) {

    if( !succeeded ) {
        NSLog(@"method failed: %@", methodName);
        completionHandler = (UIBackgroundFetchResultFailed);
    } else {
        //NSLog(@">>>>>> OUTPUT: %@", output);
        NSDictionary *responseDictionary = output;
        id response = responseDictionary[@"RetrieveMessagesResponse"][@"RetrieveMessagesResult"][@"a:MessagesResult"][@"b:MessageLabel"];
        if ([response isKindOfClass:[NSArray class]]) {
            NSArray *array = response;
            completionHandler = (UIBackgroundFetchResultNewData);
        } else {
            NSLog(@"Nothing new");
            completionHandler = (UIBackgroundFetchResultNoData);
        }
    }
}];

您可以想象,我的问题是我试图在块内设置 completionHandler。我收到错误: 变量不可赋值(缺少 __block 类型说明符)

我真的不确定如何正确实施这一点,并希望获得一些见解。任何帮助将不胜感激。

提前致谢!!

【问题讨论】:

    标签: ios objective-c objective-c-blocks


    【解决方案1】:

    你不应该分配完成块,你应该执行它并传递一个参数:

    completionHandler(UIBackgroundFetchResultNoData);
    

    请注意,为了安全起见,您还应该检查 completionHandler 是否为 nil,因为如果是,它将崩溃。

    【讨论】:

    • 非常感谢您发现我的疏忽!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-29
    • 1970-01-01
    • 1970-01-01
    • 2014-08-16
    • 1970-01-01
    • 2013-11-24
    • 2015-12-18
    相关资源
    最近更新 更多