【问题标题】:Perform task (code execution/ network call) in background when user enters/exits a location region in iOS当用户进入/退出 iOS 中的位置区域时,在后台执行任务(代码执行/网络调用)
【发布时间】:2019-05-27 23:14:02
【问题描述】:

系统:在我的应用程序中,我正在使用地理围栏(监控区域)。每当用户进入或离开受监控的区域或区域时,如果应用程序处于后台甚至终止状态,应用程序都会显示本地通知。这工作得很好。该应用程序能够显示本地通知。

现在我还需要通过 HTTP POST 调用向应用的后端服务器提交此信息(如果用户在监控区域内或之外)。

问题: 应用在 LocationManager 的委托方法中调用 API,但有时有效,有时无效。如果应用程序不处于前台状态,代码执行似乎会随机停止。

代码示例

// MARK: - Location Manager Delegate
func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {
    if region is CLCircularRegion {
        showLocalNotification(forRegion: region)// Works
        updateUserEntryAPICall(region: region) // Sometimes works
    }
}

func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) {
    if region is CLCircularRegion {
        showLocalNotification(forRegion: region) // Works
        updateUserExitAPICall(region: region) // sometime works
    }
}

我没有在 iOS 中打开后台模式功能。尽管如此,该应用程序仍然能够显示本地通知。我需要打开它才能进行网络调用吗?

请帮忙。

【问题讨论】:

    标签: ios background-process geofencing ios-background-mode


    【解决方案1】:

    这看起来您正在使用常规的URLSession 来发出您的 API 请求。您需要确保在处理后台运行的会话上执行此操作,例如通过像这样初始化它:

    let session = URLSession(configuration: .background(withIdentifier: "foo"))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-03
      • 2019-03-11
      • 1970-01-01
      • 1970-01-01
      • 2011-07-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多