【发布时间】:2022-08-02 22:05:25
【问题描述】:
我正在开发一个包含 auth 进程的 react native 库,所以我选择了 ASWebAuthenticationSession 来做这件事。 我对这个 RN 库的第一步是首先进行本地开发(在 Swift 中)。当我启动这个新库时,它同时带有objective-c bridge 和swift,我认为这两个文件都可以做同样的事情。
但是我不能从 swift 文件中正确运行 ASWebAuthenticationSession,而目标 c 可以完美地运行它,我更喜欢从 Swift 中执行它(如果我错了告诉我)
问题是,当我从 swift 运行代码时, ASWebAuthenticationSession 弹出窗口会在任何用户输入之前关闭,而不是来自 objective-c 。 这是我的代码,如果您有任何想法,请提前感谢您。
斯威夫特版本
//MyRnModule.m
@interface RCT_EXTERN_MODULE(MyRNModule, NSObject)
- (dispatch_queue_t)methodQueue
{
return dispatch_get_main_queue();
}
RCT_EXTERN_METHOD(startSecuredView:(NSURL *)uri)
//MyRnModule.swift
@objc(MyRNModule)
class MyRNModule: NSObject {
@objc func startSecuredView(_ url: URL?) {
if let url = url {
if #available(iOS 12.0, *) {
let session = ASWebAuthenticationSession(url: url, callbackURLScheme: \"\", completionHandler: { (callbackURL, error) in
print(\"completed\")
if let error = error {
print(\"erorr \\(error)\")
return
}
if let callbackURL = callbackURL {
print(\"should handle callback \\(callbackURL)\")
}
})
if #available(iOS 13.0, *) {
session.presentationContextProvider = self
}
session.start()
}
} else {
print(\"you must specify url\")
}
}
}
extension MyRNModule: ASWebAuthenticationPresentationContextProviding {
@available(iOS 13, *)
func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor{
if let keyWindow = UIApplication.shared.windows.filter {$0.isKeyWindow}.first {
return keyWindow
} else {
return ASPresentationAnchor()
}
}
}
Objective-C
@interface RCT_EXTERN_MODULE(MyRNModule, NSObject)
- (dispatch_queue_t)methodQueue
{
return dispatch_get_main_queue();
}
RCT_EXPORT_METHOD(startSecuredView:(NSURL *)url)
{
if (!url) {
RCTLogError(@\"You must specify a url.\");
return;
}
if (@available(iOS 12.0, *)) {
ASWebAuthenticationSession* session =
[[ASWebAuthenticationSession alloc] initWithURL:url
callbackURLScheme: @\"\"
completionHandler:^(NSURL * _Nullable callbackURL,
NSError * _Nullable error) {
_authenticationVCC = nil;
if (callbackURL) {
[RCTSharedApplication() openURL:callbackURL];
}
}];
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000
if (@available(iOS 13.0, *)) {
session.presentationContextProvider = self;
}
#endif
_authenticationVCC = session;
[session 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
代码似乎反映了相同的过程,只是翻译了,我不知道我错过了什么,因为MyRNModule. startSecuredView(\"https://some.url\") 的调用行为不一样
标签: ios swift react-native react-native-modules aswebauthenticationsession