Alamofire的问题挑战委托和逃避关闭

时间:2017-05-13 00:10:20

标签: swift swift3 alamofire

我正在使用AF并使用它的委托来捕获我的服务器返回的身份验证质询。

#pragma comment(lib, "windowsapp") 
#pragma comment(lib, "pathcch")

#include <winrt/Windows.Storage.Streams.h>
#include <winrt/Windows.Graphics.Imaging.h>
#include <winrt/Windows.Media.Ocr.h>
#include <winrt/Windows.Networking.Sockets.h>

#include <pathcch.h>

using namespace winrt;
using namespace std::chrono;

using namespace Windows::Foundation;
using namespace Windows::Storage;
using namespace Windows::Storage::Streams;
using namespace Windows::Graphics::Imaging;
using namespace Windows::Media::Ocr;

hstring MessagePath()
{
    wchar_t buffer[1024]{};
    GetCurrentDirectory(_countof(buffer), buffer);
    check_hresult(PathCchAppendEx(buffer, _countof(buffer), L"message.png", PATHCCH_ALLOW_LONG_PATHS));
    return buffer;
}

IAsyncOperation<hstring> AsyncSample()
{
    StorageFile file = co_await StorageFile::GetFileFromPathAsync(MessagePath());
    IRandomAccessStream stream = co_await file.OpenAsync(FileAccessMode::Read);

    BitmapDecoder decoder = co_await BitmapDecoder::CreateAsync(stream);
    SoftwareBitmap bitmap = co_await decoder.GetSoftwareBitmapAsync();

    OcrEngine engine = OcrEngine::TryCreateFromUserProfileLanguages();
    OcrResult result = co_await engine.RecognizeAsync(bitmap);
    return result.Text();
}

int main()
{
    init_apartment();

    try
    {
        printf("%ls\n", AsyncSample().get().c_str());
    }
    catch (hresult_error const & e)
    {
        printf("hresult_error: (0x%8X) %ls\n", e.code(), e.message().c_str());
    }

    return 0;
}

我有问题:

  1. 如果我按原样使用上面的代码,我会

    错误:“将非转义参数'completionHander'传递给期望@escaping闭包的函数”

  2. 如果我使函数handleAuthenticationSession的参数无法转义,我得到:

    func connectGetRequest(_ url : URL){
    
        let sessionManager = Alamofire.SessionManager.default
        sessionManager.request(url).responseString { response in
            print("Response String: \(response.result.value)")
        }
        let delegate: Alamofire.SessionDelegate = sessionManager.delegate
    
    
        delegate.taskDidReceiveChallengeWithCompletion = { session, task, challenge,  completionHander in
            print("session is \(session), task is \(task) challenge is \(challenge.protectionSpace.authenticationMethod) and handler is \(completionHander)")
            if(challenge.protectionSpace.authenticationMethod == "NSURLAuthenticationMethodServerTrust"){
    
                completionHander(.performDefaultHandling,nil)
            }else{
    
                print("challenge type is \(challenge.protectionSpace.authenticationMethod)")
    
          // Following line give me the error: "passing non-escaping parameter 'completionHander' to function expecting an @escaping closure"
    
    self.handleAuthenticationforSession(challenge,completionHandler:  completionHander)
            }
        }
    
        delegate.dataTaskDidReceiveData = {session , task, data in
    
            print("received data \(data)")
        }
    
    }
    
    
    func handleAuthenticationforSession(_ challenge: URLAuthenticationChallenge,completionHandler:   @escaping (Foundation.URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
    
    
            Authhandler.handleChallenge(forURLSessionChallenge: challenge, completionHandler: completionHandler)
    
    
    }
    
  3. 错误:“关闭使用非转义参数'完成'可能允许它转义”

    另外,来自AuthHandler类的handleChallenge方法(它是obj-c框架的一部分)如下所示。

     func handleAuthenticationforSession(_ challenge: URLAuthenticationChallenge,
      completionHandler:   (Foundation.URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
    
         }
    

    所以基本上我陷入了僵局,而我使用Alamofire的闭包语法来委派auth挑战。

1 个答案:

答案 0 :(得分:1)

在我看来,问题的缺失部分是Authhandler.handleChallenge中的完成处理程序是否正在转义。是的,对吧?

但是taskDidReceiveChallengeWithCompletion completionHandler是非转义的。因此,当你不允许它逃脱时,你正试图弄清楚如何让它逃脱。

看看Alamofire源代码,大约3个月前,他们将completionHandler改为@escaping!见这里:https://github.com/Alamofire/Alamofire/commit/b03b43cc381ec02eb9855085427186ef89055eef

在PR合并之后,您需要更新到Alamofire的版本,或者您需要弄清楚如何以完全不转义的方式处理completionHandler。这意味着,您的Authhandler.handleChallenge无法使用转义版的完成处理程序。