YouSS
YouSS

Reputation: 570

NSMethodSignature & NSInvocation equivalent in swift 2

How can i writte this class in swift 2 ? NSMethodSignature & NSInvocation doesn't exist anymore in swift 2

@implementation MyAuth

- (void)authorizeRequest:(NSMutableURLRequest *)request
                delegate:(id)delegate
       didFinishSelector:(SEL)sel {
    if (request) {
        NSString *value = [NSString stringWithFormat:@"%s %@", GTM_OAUTH2_BEARER, self.accessToken];
        [request setValue:value forHTTPHeaderField:@"Authorization"];
    }

    NSMethodSignature *sig = [delegate methodSignatureForSelector:sel];
    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:sig];
    [invocation setSelector:sel];
    [invocation setTarget:delegate];
    [invocation setArgument:(__bridge void *)(self) atIndex:2];
    [invocation setArgument:&request atIndex:3];
    [invocation invoke];
}

- (void)authorizeRequest:(NSMutableURLRequest *)request
       completionHandler:(void (^)(NSError *error))handler {
    if (request) {
        NSString *value = [NSString stringWithFormat:@"%@ %@", @"Bearer", self.accessToken];
        [request setValue:value forHTTPHeaderField:@"Authorization"];
    }
}

Thank's in advance

Upvotes: 1

Views: 2428

Answers (1)

newacct
newacct

Reputation: 122489

NSInvocation is not available in Swift. But, in this case, NSInvocation is actually not necessary. We know from the way you are setting the arguments that you are always going to call a method with two parameters object-pointer type. (Assuming you meant &self instead of self for index 2.) You can do that with performSelector:withObject:withObject:.

[delegate performSelector:sel withObject:self withObject:request]

This is available in Swift 2:

delegate?.performSelector(sel, withObject:self, withObject:request)

P.S. It's really weird because it seems you have another version of the method which takes a completion handler, which would be perfect for Swift, except that the body seems to be incomplete, and the type of the completion handler is not right as it doesn't take request.

Upvotes: 1

Related Questions