Unity has a network connection check function ʻApplication.internetReachability`, but I dared to make a native Swift plugin using ** NWPathMonitor **.
Use NWPath Monitor, which is simpler than Reachability, to detect network connection status on iOS. --Qiita For the processing around Swift, I referred to the article here.
UniNWPathMonitor.swift
monitor.pathUpdateHandler = { path in
if path.status == .satisfied {
// connected
self._onCallback("1")
} else {
// No connected
self._onCallback("0")
}
}
If you are connected using the NWPathMonitor instance (monitor), " 1 "
will be returned, and if you are disconnected, " 0 "
will be returned with a preset callback.
API_AVAILABLE(ios(12.0))
UniNWPathMonitor *_monitor;
Since iOS12 or later is required to use NWPathMonitor this time, declare that iOS12 or later is required with ʻAPI_AVAILABLE`.
UniNWPathMonitorBridge.mm
[_monitor setCallbackOnCallback:^(NSString * value) {
UnitySendMessage("UniNWPathMonitor", "Noti", [value UTF8String]);
}];
Set a callback for UniNWPathMonitor. When the callback is returned, use ʻUnitySendMessage` to return the connection information to the Unity side.
For the description of Objective-C ++, please refer to the article here that I wrote earlier. [Unity] Shortest implementation to run Swift from C # in recent Unity-Qiita
This is how it is used on the Unity side. Just run StartMonitor on UniNWPathMonitor and set the callback.
Sample.cs
void Start()
{
UniNWPathMonitor.StartMonitor();
UniNWPathMonitor.onChangeNetworkStatus += status =>
{
if (status == UniNWPathMonitor.NetworkStatus.satisfied)
//connecting
else
//Cutting
};
}
Click here for what I actually made. I turn Wifi on and off and receive callbacks on the Unity side. There seems to be a slight lag until the callback is returned to Unity after switching.
As I said at the beginning, this plugin is not required for Buchake Unity because ** Application.internetReachability ** exists. * I made it because I wanted to make it.
For me, I learned a lot by actually making it. I'm glad I had the opportunity to learn about Swift, which I'm currently studying, such as the Swift callback grammar that came out for the first time and how to make iOS 12 or later mandatory.
All sources are uploaded below, so please refer to them. https://github.com/baobao/UniNWPathMonitor
Recommended Posts