【问题标题】:How to properly port this code to Swift如何正确将此代码移植到 Swift
【发布时间】:2015-03-14 11:28:17
【问题描述】:

PubNub 在 iOS SDK 中提供了这个 sn-p 以在客户端因应用退出活动而被挂起之前调用一些客户端方法:

- (void)pubnubClient:(PubNub *)client willSuspendWithBlock:(void(^)(void(^)(void(^)(void))))preSuspensionBlock {

if ([client isConnected]) {

    preSuspensionBlock(^(void(^completionBlock)(void)){

        [client sendMessage:@"Hello my friend" toChannel:[PNChannel channelWithName:@"boom"]
        withCompletionBlock:^(PNMessageState state, id data) {

            if (state != PNMessageSending) {

                NSString *message = @"Message has been sent";
                if (state == PNMessageSendingError) {

                    // Handle message sending error
                }

                // Always call this block as soon as required amount of tasks completed.
                completionBlock();
            }
        }];
    });
}
}

现在 XCode 足够聪明,可以将方法声明中的疯狂块语法转换为这个,我想这很好:

public func pubnubClient(client: PubNub!, willSuspendWithBlock preSuspensionBlock: (((((() -> Void)!) -> Void)!) -> Void)!)

我真的不知道如何移植这条线: preSuspensionBlock(^(void(^completionBlock)(void))

块语法总是让我很生气。

【问题讨论】:

  • 我也一样...你找到什么了吗?
  • 如果您的问题出在背景上,我最终会使用“shouldRunClientInBackground”来正确使用带有背景的 pubnub...

标签: ios iphone swift pubnub


【解决方案1】:

objective-c 代码是一个 preSuspension 方法接受一个块,该块返回一个不接受任何参数的块。试试这样的:

  var x: (()-> () -> Void) = { () -> ()->Void in
        return {() -> Void in
            println("this is returned inner void block")
        }
    }

    preSuspensionBlock(x);

【讨论】:

    【解决方案2】:

    PubNub.sendMessage(chatMessage, googleCloudNotification: nil, toChannel:chatChannel, storeInHistory: true) { (state, obj) -> Void in

           if (state != PNMessageState.Sending){
              println("Message has been sent")
             if(state == PNMessageState.SendingError){
               completionHandler(responseStatus: RespStatus.unExpectedServerError)
             }
             else{
                completionHandler(responseStatus: RespStatus.responseSuccess)
            }
           }
    
        }
    

    【讨论】:

      猜你喜欢
      • 2013-01-18
      • 2011-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-20
      • 2011-08-30
      相关资源
      最近更新 更多