我正在创建一个地理定位应用程序,并且我想自动启动每次向我发送坐标的服务。
看着互联网,我读到技术上在 ios 上是不可能的,但是有一些方法可以克服这个问题。
我想采用静默通知。
我实现了该方法,当应用程序处于后台时一切正常,但是当我打开设备并发送静默通知时,事件:didReceiveRemoteNotification:不会触发。甚至当我从应用程序切换器关闭应用程序然后发送通知时也不会触发。
我想知道如果你能做到的话,是否有什么问题。
ps:我正在使用:didReceiveRemoteNotification:并且没有应用程序:didReceiveRemoteNotification:fetchCompletionHandler:(这可能是问题吗?)
我在 AppDelegate 中的代码:
public override async void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo, Action<UIBackgroundFetchResult>
completionHandler)
{
await Manager.SendPosition(completionHandler);
}
在我的 FinishedLaunching 中:
if (Convert.ToInt16(UIDevice.CurrentDevice.SystemVersion.Split('.')[0].ToString()) < 8)
{
UIRemoteNotificationType notificationTypes = UIRemoteNotificationType.Alert | UIRemoteNotificationType.Badge |
UIRemoteNotificationType.Sound;
UIApplication.SharedApplication.RegisterForRemoteNotificationTypes(notificationTypes);
}
else
{
UIUserNotificationType notificationTypes = UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound;
var settings = UIUserNotificationSettings.GetSettingsForTypes(notificationTypes, new NSSet(new string[] { }));
UIApplication.SharedApplication.RegisterUserNotificationSettings(settings);
UIApplication.SharedApplication.RegisterForRemoteNotifications();
}
在我的 info.plist 中:
<key>UIBackgroundModes</key>
<array>
<string>location</string>
<string>remote-notification</string>
</array>
更新:
public async Task<bool> SendPosition(Action<UIBackgroundFetchResult> completionHandler = null)
{
StartLocationUpdates();
var setting = ConnectDb()?.Table<Settings>().FirstOrDefault() ?? new Settings();
_currentLong = 14.52538;
_currentLat = 36.82842;
if (_currentLong != 0 && _currentLat != 0)// && setting.TimeNotification != 0)
{
var objectSend = new
{
unique_key = setting.UniqueKey,
lat = _currentLat,
lng = _currentLong,
idPlayerOneSignal = setting.IdPlayerOneSignal,
token = ""
};
var client = new HttpClient { BaseAddress = new Uri("http://amywebservice.com/") };
var data = JsonConvert.SerializeObject(objectSend);
var content = new StringContent(data, Encoding.UTF8, "application/json");
var response = await client.PostAsync("api/setPosition", content);
if (response.IsSuccessStatusCode)
{
var successResult = response.Content.ReadAsStringAsync().Result;
Debug.WriteLine("k", successResult);
if (completionHandler != null)
{
completionHandler(UIBackgroundFetchResult.NoData);
}
return true;
}
else
{
var failureResulr = response.Content.ReadAsStringAsync().Result;
Debug.WriteLine("f", failureResulr);
if (completionHandler != null)
{
completionHandler(UIBackgroundFetchResult.NoData);
}
return false;
}
}
return false;
}
但不起作用,如果我发送静默通知,我只会运行第一次飞行,并且只有当应用程序位于后台时。
如果我打开手机并通知通知将不起作用。