8

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?

1
  • what error are you getting?
    – Connor
    Commented Jun 19, 2014 at 1:35

3 Answers 3

15
  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)
    }
    
1
  • This could be cleaned up even a little bit more: (1) the method itself doesn't need a return type since it is Void (so you can leave off the -> () in the method signature), and (2) since for NSURLCredential the type of the persistence argument is known, you can just provide the option that you want to use, .ForSession
    – fqdn
    Commented Jun 19, 2014 at 1:50
1

This code may help ->

 AFAppDotNetAPIClient.sharedClient().GET("User", parameters:nil, success:{ (task : NSURLSessionDataTask!, JSON: AnyObject!) in
        // within block....

        }, failure:nil)
0

Your type is backwards — you want the completion handler to take two arguments and return none, but you've defined it as a function that takes no arguments and returns a pair. Flop the two sides of the arrow.

Not the answer you're looking for? Browse other questions tagged or ask your own question.