由於我沒有收到這方面的任何反饋,我弄清楚如何做到這一點。這是答案。
爲了控制我使用loadView
方法從UIViewController
生命週期中查看哪個視圖。當應用程序首先需要從UIViewController
獲得view
屬性時,會觸發此方法。所以這是懶加載。當用戶從UIViewController
api調用loadViewIfNeeded()
時,也會觸發此方法。在這個方法的主體中,你需要非常小心,不要讀取view
屬性,因爲這將再次調用loadView
,並且您將有遞歸循環。
我的這個方法的實現如下。我需要告訴用戶是否已登錄或未包含應用程序,並根據此選擇要加載的視圖。
override func loadView() {
// check in shared Keychain if user is authenticated
self.userAuthenticated = userService.isAuthenticated()
if self.userAuthenticated {
// load default view of the ShareViewController
super.loadView()
} else {
// if user is not logged in show only alert view controller with transparent dummy view
let view = UIView()
self.view = view
}
}
如果用戶沒有登錄我
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let context = self.extensionContext!
if !self.userAuthenticated {
let alert = UIAlertController(title: "Error", message: "User not logged in", preferredStyle: .alert)
let cancel = UIAlertAction(title: "Cancel", style: .cancel) { _ in
context.completeRequest(returningItems: nil, completionHandler: nil)
}
let login = UIAlertAction(title: "Log In", style: .default, handler: { _ in
let url = URL(string: "fashionapp://login")!
// This is utility method written in Objective-C.
// I don't know yet if it passes Apple Review process or not.
// We will see ;)
self.open(url, options: [:], completionHandler: nil)
context.completeRequest(returningItems: nil, completionHandler: nil)
})
alert.addAction(cancel)
alert.addAction(login)
present(alert, animated: true, completion: nil)
}
}
顯示警告這裏是包含從份額擴展的應用程序打開的方法。我希望它會有用,Apple會在沒有任何問題的情況下對此進行審查。它寫在Objective-C
中,因爲在Swift
中沒有NSInvocation
類,因此只能使用最多兩個參數執行選擇器。
#import <UIKit/UIKit.h>
@interface UIViewController (OpenURL)
- (void)openURL:(nonnull NSURL *)url
options:(nonnull NSDictionary<NSString *, id> *)options
completionHandler:(void (^ __nullable)(BOOL success))completion;
@end
並執行。
#import "UIViewController+OpenURL.h"
@implementation UIViewController (OpenURL)
- (void)openURL:(nonnull NSURL *)url
options:(nonnull NSDictionary<NSString *, id> *)options
completionHandler:(void (^ __nullable)(BOOL success))completion {
SEL selector = NSSelectorFromString(@"openURL:options:completionHandler:");
UIResponder* responder = self;
while ((responder = [responder nextResponder]) != nil) {
if([responder respondsToSelector:selector] == true) {
NSMethodSignature *methodSignature = [responder methodSignatureForSelector:selector];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSignature];
[invocation setTarget: responder];
[invocation setSelector: selector];
[invocation setArgument: &url atIndex: 2];
[invocation setArgument: &options atIndex:3];
[invocation setArgument: &completion atIndex: 4];
[invocation invoke];
break;
}
}
}
@end
你能解釋一下如何使用這段代碼嗎?我堅持這個共享的東西,並沒有幫助在網上找到。 –