1

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

Moin Shirazi
  • 4,372
  • 2
  • 26
  • 38
YouSS
  • 560
  • 7
  • 20
  • 1
    I'm not quite sure why you use NSInvocation in the first place. Why do you pass a ptr to the ptr of the request to the delegate? The request is mutable already. In Swift you would probably use a 'didFinishBlock' instead of a 'didFinishSelector'. – hnh Apr 01 '16 at 00:21
  • i didn't do this, i just found it and i want to convert it in swift2 but the 2 classes doesn't exist anymore – YouSS Apr 01 '16 at 01:12
  • By the way, this Objective-C code is wrong. The line `[invocation setArgument:(__bridge void *)(self) atIndex:2];` is wrong. `-[NSInvocation setArgument:atIndex:]` takes a pointer to the thing to set as argument. You are passing `self`, which is a pointer to an object, and an object cannot be manipulated directly. If you want to set `self` as the argument, you must pass `&self` instead. – newacct Apr 05 '16 at 04:39

1 Answers1

1

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.

newacct
  • 119,665
  • 29
  • 163
  • 224