flutter通过通道调用原生方法
/// 只有是iOS设备才显示苹果登陆
if (Platform.isIOS){
list.add(GestureDetector(
child: Image.asset(
QPictureManager.instance.getAssetsImage(QAssets.icon_apple),
gaplessPlayback: true,
width: 48.rpx,
height: 48.rpx,
),
onTap: loginApple,
));
}
/// 请求登陆与原生交互
loginApple() async {
const platform = const MethodChannel("login");
var result;
Map<dynamic, dynamic> params;
try {
result = await platform.invokeMethod("login_apple", []);
params = result as Map<dynamic, dynamic>;
}catch(e){
QLog("苹果登陆失败!${e}", StackTrace.current);
}
if (params == null){
QLog("苹果登陆获取OpenId失败!", StackTrace.current);
return;
}
final openId = params["openId"];
if (openId.isEmpty){
QLog("苹果登陆获取OpenId为空!", StackTrace.current);
return;
}
QLog("苹果登陆开始请求数据!", StackTrace.current);
}
iOS Swift原生注册
import UIKit
import AuthenticationServices
class QLoginFlutterPlugin: NSObject, FlutterPlugin, ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding {
static let instance = QLoginFlutterPlugin()
static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel.init(name: "login", binaryMessenger: registrar.messenger())
registrar.addMethodCallDelegate(instance, channel: channel)
}
var resultLogin : FlutterResult?
func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
if call.method.elementsEqual("login_apple") {
if #available(iOS 13.0, *) {
resultLogin = result
let request = ASAuthorizationAppleIDProvider().createRequest()
request.requestedScopes = [.fullName, .email]
let authController = ASAuthorizationController(authorizationRequests: [request])
authController.delegate = self
authController.presentationContextProvider = self
authController.performRequests()//启动授权
}
}
}
@available(iOS 13.0, *)
func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
return UIApplication.shared.keyWindow!
}
@available(iOS 13.0, *)
func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
guard let credential = authorization.credential as? ASAuthorizationAppleIDCredential else {
return
}
let params = ["openId": credential.user]
resultLogin?(params)
}
@available(iOS 13.0, *)
func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
}
}
AppDelegate注册
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
GeneratedPluginRegistrant.register(with: self)
QLoginFlutterPlugin.register(with: registrar(forPlugin: "QLoginFlutterPlugin"))
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
Signing & Capabilities添加Sign In with Apple