如何正确地将此代码移植到Swift

时间:2015-03-14 11:28:18

标签: ios iphone swift pubnub

PubNub在iOS SDK中提供此代码段,以便在应用程序从活动状态重新启动后暂停客户端之前调用某些客户端方法:

- (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))

阻止语法总是杀了我。

2 个答案:

答案 0 :(得分:0)

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

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

    preSuspensionBlock(x);

答案 1 :(得分:-1)

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

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

    }