「Unity/Native連携/Swiftバックグランド通知」の版間の差分
提供: 初心者エンジニアの簡易メモ
| 行1: | 行1: | ||
| + | ボタンを押して、10秒後に、バックグラウンドに移動してたら、通知が入る。 | ||
==Unity側== | ==Unity側== | ||
<pre> | <pre> | ||
2024年9月10日 (火) 22:46時点における最新版
ボタンを押して、10秒後に、バックグラウンドに移動してたら、通知が入る。
Unity側
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;
#if UNITY_IPHONE
using System.Runtime.InteropServices;
#endif
public class RenkeiScene : MonoBehaviour
{
#if UNITY_IPHONE
// Swift の関数を宣言 (Objective-C のブリッジとして)
[DllImport("__Internal")]
private static extern void _scheduleNotification(int second);
#endif
[SerializeField] Button alermButton;
void Start()
{
alermButton.onClick.AddListener(CallMethodAlarm);
alermCancelButton.onClick.AddListener(CallMethodAlarmCancel);
}
void CallMethodAlarm()
{
#if UNITY_IOS && !UNITY_EDITOR
ScheduleNotification(10);
#endif
}
#if UNITY_IOS && !UNITY_EDITOR
// 通知をスケジュールするメソッド
public void ScheduleNotification(int second)
{
_scheduleNotification(second);
}
#endif
}
Swift,Objective-C側
NotificationManager.swift
import Foundation
import UserNotifications
@objc public class NotificationManager: NSObject {
// 通知を設定するメソッド
// @objc public static func scheduleNotification(_ hour: Int, _ minute: Int, _ second: Int) {
@objc public static func scheduleNotification(_ second: Int) {
let center = UNUserNotificationCenter.current()
print("scheduleNotification: \(second)秒後に通知をスケジュールします")
// 通知の権限をリクエスト
center.requestAuthorization(options: [.alert, .sound]) { granted, error in
if granted {
print("通知の権限が許可されました")
// 通知のコンテンツを作成
let content = UNMutableNotificationContent()
content.title = "アラーム通知"
content.body = "指定した時間が経過しました!"
content.sound = UNNotificationSound.default
// x 秒後に通知するトリガーを作成
let triggerTime = TimeInterval(second)
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: triggerTime, repeats: false)
// 通知リクエストを作成
let request = UNNotificationRequest(identifier: "AlarmNotification", content: content, trigger: trigger)
// 通知を登録
center.add(request) { error in
if let error = error {
print("通知の登録に失敗しました: \(error)")
} else {
print("通知が正常に登録されました")
}
}
} else {
print("通知の権限が拒否されました")
}
}
}
}
UnityBridge.mm
#import <UnityFramework/UnityFramework-Swift.h>
extern "C" {
void _scheduleNotification(int second) {
// Swift の NotificationManager クラスのメソッドを呼び出す
// [NotificationManager scheduleNotification:hour minute:minute second:second];
[NotificationManager scheduleNotification:second];
}
}
scheduleNotificationの引数を時分秒で渡したかったが、引数2つ以上の渡し方がわからず・・。とりあえず秒だけ渡した。
