将以下swift示例中的代码转换为C#(Xamarin),以便在SFSafariViewController内接收到Paypal令牌时通知应用程序,但它不会触发该方法。
将swift转换为C#,如下所示,但在用户登录PayPal并收到令牌后,Safari并未关闭以触发SetupMerchant()
UrlSchemes也设置为retailsdksampleapp以匹配来自PayPal的示例swift应用程序。
SafariDelegate safariDelegate = new SafariDelegate(this);
NSNotificationCenter.DefaultCenter.AddObserver(new NSString("kCloseSafariViewControllerNotification"), safariDelegate.SetupMerchant);
void loadBrowser()
{
var url = new NSUrl("https://paypalauth.herokuapp.com/toPayPal/" + Application.paypalEnvironment + "?returnTokenOnQueryString=true");
var svc = new SFSafariViewController(url);
svc.Delegate = safariDelegate;
this.PresentViewController(svc, true, null);
}
public class SafariDelegate : SFSafariViewControllerDelegate
{
ViewController _controller = null;
public SafariDelegate(ViewController controller)
{
_controller = controller;
}
public void SetupMerchant(NSNotification notification)
{
// Dismiss the SFSafariViewController when the notification of token has been received.
this._controller.PresentedViewController?.DismissViewController(true, () => { });
// Grab the token(s) from the notification and pass it into the merchant initialize call to set up
// the merchant. Upon successful initialization, the 'Connect Card Reader' button will be
// enabled for use.
var accessToken = notification.Object.ToString();
}
}
从Paypal运行swift示例应用程序时,它会在登录后关闭浏览器(SFSafariViewController)并触发SetupMerchant()但不会触发C#代码。可能缺少步骤或无效的代码转换。
如果Safari控制器没有关闭并且你有正确的UrlScheme set(),那么你在OpenUrl
类中缺少AppDelegate
覆盖,它会监听你的app的url方案并发布你的视图控制器正在监听的通知。
[Export("application:openURL:sourceApplication:annotation:")]
public bool OpenUrl(UIApplication application, NSUrl url, string sourceApplication, NSObject annotation)
{
if (sourceApplication == "com.apple.SafariViewService")
{
var dict = HttpUtility.ParseQueryString(url.Query);
var token = dict["access_token"];
NSNotificationCenter.DefaultCenter.PostNotificationName("kCloseSafariViewControllerNotification", new NSString(token));
};
return true;
}