Xamarin iOS:使用NSURLSession API时出现DidReceiveChallenge问题

时间:2017-02-11 03:32:29

标签: ios xamarin xamarin.ios nsurlsession

我正在编写一个Xamarin本机iOS应用程序,并使用nsurlsession命中一个http端点,这为我提供了基本类型身份验证挑战。

我的问题是我的委托中的DidReceiveChallenge方法没有被调用:

我的代码:

NSUrl url = new NSUrl("http://httpbin.org/basic-auth/test/test");
        NSUrlRequest request = new NSUrlRequest(url);
        NSUrlSession session = null;
        NSUrlSessionConfiguration myConfig = NSUrlSessionConfiguration.DefaultSessionConfiguration;
        MySessionDelegate myDelegate = new MySessionDelegate();
        NSOperationQueue myQueue = new NSOperationQueue();
        session = NSUrlSession.FromConfiguration(myConfig, myDelegate, myQueue);

        NSUrlSessionTask task = session.CreateDataTask(request, (data, response, error) =>
        {
            Debug.WriteLine("data is"+data+"response is"+response+"error is "+error);

        });


        task.Resume();

我的代表班:

public class MySessionDelegate : NSUrlSessionDelegate
{

    public override void DidReceiveChallenge(NSUrlSession session, NSUrlAuthenticationChallenge challenge, Action<NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler)
    {
        Debug.WriteLine("challenge is"+challenge.ProtectionSpace.AuthenticationMethod);
        base.DidReceiveChallenge(session, challenge, completionHandler);
    }


}

我目前正在获取的应用程序输出:

data isresponse is<NSHTTPURLResponse: 0x170437700> { URL: http://httpbin.org/basic-auth/nsharma/P@ssw0rd } { status code: 401, headers {
    "Access-Control-Allow-Credentials" = true;
    "Access-Control-Allow-Origin" = "*";
    "Content-Length" = 0;
    Date = "Sat, 11 Feb 2017 03:18:45 GMT";
    Server = nginx;
    Via = "1.1 nas58.airwlab.com";
    "Www-Authenticate" = "Basic realm=\"Fake Realm\"";
} }error is 

你可以观察到,由于基本的auth挑战,我可以点击发出401的网址。通常我希望流程在我的委托实例中调用DidReceiveChallenge方法,但它从不调用它并完成执行。

1 个答案:

答案 0 :(得分:0)

使用了错误的Delegate类:

public class MySessionDelegate : NSUrlSessionDelegate{
public override void DidReceiveChallenge(NSUrlSession session, 
NSUrlSessionTask task, NSUrlAuthenticationChallenge challenge, 
Action<NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler){

}
}