简体   繁体   中英

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?

  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) } 

This code may help ->

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

        }, failure:nil)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM