Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift syntax for block with completionHandler... in delegate method

This is a wrinkle on the regular NSURLSession completion block problem, which I'm having a heck of a time resolving into Swift syntax. The method is the authentication delegate callback, which is invoked on auth challenge; the developer calls the completion block with NSURLCredential, NSError.

The Objective-C method looks like this:

-(void) provideUsernamePasswordForAuthChallenge:(NSURLAuthenticationChallenge *)authChallenge completionHandler:(void (^)(NSURLCredential *, NSError *))completionHandler{

    NSURLCredential* credential = [NSURLCredential credentialWithUser:@"myname" 
                                                             password:@"mypass" 
                                                          persistence:NSURLCredentialPersistenceForSession];
    completionHandler(credential, nil);
}

The closest I think I've gotten in Swift, is this:

func provideUsernamePasswordForAuthChallenge(authChallenge: NSURLAuthenticationChallenge!,  completionHandler:(() -> (NSURLCredential?, NSError?)) {

    var cred = NSURLCredential(user: "myname", password: "mypass", persistence: NSURLCredentialPersistence.ForSession)
    return (cred, nil)
})

But, it's still barfing. Any recommendations?

like image 366
Stan Avatar asked Jun 19 '14 01:06

Stan


1 Answers

  1. a void function is (Type1, Type2)->()
  2. you need to add the ->() for the method itself
  3. You need to call completionHandler with (cred, nil), not return a tuple

    func provideUsernamePasswordForAuthChallenge(authChallenge: NSURLAuthenticationChallenge!,  completionHandler:(NSURLCredential?, NSError?)->()) ->() {
    
       var cred = 
          NSURLCredential(user: "myname", password: "mypass", 
             persistence: NSURLCredentialPersistence.ForSession)
       completionHandler(cred, nil)
    }
    
like image 65
Lou Franco Avatar answered Oct 01 '22 13:10

Lou Franco