user3011685
user3011685

Reputation: 1023

Swift Block Syntax with Objective-C Function [Venmo-iOS-SDK]

I'm currently trying to use the Venmo-iOS-SDK for an application I am working on. The SDK is in objective-C, while I'm trying to use it with a swift app.

I'm having trouble translating the syntax of a completion obj-c block to swift. I found sample code implementing a function I want to use.

- (IBAction)logInButtonAction:(id)sender { 
  [[Venmo sharedInstance] requestPermissions:@[VENPermissionMakePayments,
                                             VENPermissionAccessProfile]
                     withCompletionHandler:^(BOOL success, NSError *error) {
                         if (success) {
                             NSLog("Success")
                         } else {
                             NSLog("Failure")
                     }
 }];
}

I've tried doing this

@IBAction func loginButtonAction(sender: AnyObject){
    Venmo.sharedInstance().requestPermissions([VENPermissionMakePayments, VENPermissionAccessPhone], withCompletionHandler: { (success: Bool, error: NSErrorPointer) -> Void in
        if success{
            println("Yes")
        }else{
            println("No")
        }
    })
}

But get the error

"Cannot invoke 'requestsPermissions with an argument list of type '([String], withCompletionHandler: (Bool, NSError) -> Void)'

Is this a problem with how i'm translating the block? Or something else. Looking at the Venmo-SDK the obj-C functions are defined like this

- (void)requestPermissions:(NSArray *)permissions withCompletionHandler:(VENOAuthCompletionHandler)handler;

and

- (void)requestPermissions:(NSArray *)permissions withCompletionHandler:(VENOAuthCompletionHandler)handler;

Upvotes: 0

Views: 123

Answers (1)

Kai Schaller
Kai Schaller

Reputation: 443

You can write it like this (note the lack of types on the completion handler params):

@IBAction func loginButtonAction(sender: AnyObject) {
    Venmo.sharedInstance().requestPermissions([VENPermissionMakePayments, VENPermissionAccessPhone], withCompletionHandler: { (success, error) -> Void in
        // code here
    })
}

A bit more concise with Swift 2 syntax would be omitting the -> Void and explicit withCompletionHandler: parameter:

@IBAction func loginButtonAction(sender: AnyObject) {
    Venmo.sharedInstance().requestPermissions([VENPermissionMakePayments, VENPermissionAccessPhone]) { (success, error) in
        // code here
    }
}

You'll also want to make sure you change your println statements to print.

Upvotes: 1

Related Questions