iOS 13上的ASWebAuthenticationSession

时间:2019-10-04 13:28:25

标签: ios objective-c flutter

我安装了iOS 13,通过Safari的身份验证不再起作用。 除了self.authSessionAS.presentationContextProvider = self;

,我在iOS 12上具有相同的配置
self.authSessionAS = [[ASWebAuthenticationSession alloc]initWithURL:[[NSURL alloc] initWithString:self.authUrl] callbackURLScheme:@"app://" completionHandler:^(NSURL * _Nullable callbackURL, NSError * _Nullable error) {
    if(callbackURL)
    {
        self.resultStream(callbackURL.absoluteString);
    }else
    {
        self.resultStream(@"");
    }
    self.resultStream = NULL;
}];

self.authSessionAS.presentationContextProvider = self;
[self.authSessionAS start];

2 个答案:

答案 0 :(得分:0)

我找到了解决方法

在实现上方添加。

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000
@interface AppDelegate() <ASWebAuthenticationPresentationContextProviding>
@end
#endif

在您的Auth代码中。

self.authSessionAS = [[ASWebAuthenticationSession alloc]initWithURL:[[NSURL alloc] initWithString:self.authUrl] callbackURLScheme:@"app://" completionHandler:^(NSURL * _Nullable callbackURL, NSError * _Nullable error) {
    if(callbackURL)
    {
        self.resultStream(callbackURL.absoluteString);
    }else
    {
        self.resultStream(@"");
    }
    self.resultStream = NULL;
}];

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000
if (@available(iOS 13, *)) {
    self.authSessionAS.presentationContextProvider = self;
}
#endif

[self.authSessionAS start];

添加方法

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000
#pragma mark - ASWebAuthenticationPresentationContextProviding
- (ASPresentationAnchor)presentationAnchorForWebAuthenticationSession:(ASWebAuthenticationSession *)session  API_AVAILABLE(ios(13.0)){
   return UIApplication.sharedApplication.keyWindow;
}
#endif

答案 1 :(得分:0)

UIScene内有时很难确定正确的上下文,并且以上所有示例可能均无法按预期工作。

import AuthenticationServices
import UIKit

public protocol AuthContextProvider where Self: ASWebAuthenticationPresentationContextProviding {

  func clear()
}

final class ContextProvider: NSObject, AuthContextProvider {

  private var context: ASPresentationAnchor?

  // MARK: - ASWebAuthenticationPresentationContextProviding

  public func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor {
    let window = UIWindow()
    window.makeKeyAndVisible()
    self.context = window
    return window
  }

  public func clear() {
    context = nil
  }
}

然后在您的代码中的某处:

  var contextProvider: AuthContextProvider?
  var session: NSObject?
  

并通过身份验证功能调用功能

  let session = ASWebAuthenticationSession(url: url, callbackURLScheme: callbackScheme) {
    url, error in

    if #available(iOS 13, *) {
      self.contextProvider?.clear() // clear context
    }

    completion(url, error)
  }

  self.session = session // retain session

  if #available(iOS 13, *) {
    self.contextProvider = ContextProvider() // retain context
    session.presentationContextProvider = self.contextProvider
  }

  session.start()