Это мой код NSURLSession, по сути, я пытаюсь загрузить файл в S3, используя HealthKit в расписании в фоновом режиме. Я просто хочу установить приложение, и этот процесс загрузки должен происходить в графике ежедневно, даже если приложение находится в фоновом режиме. < /P>
import UIKit
class AppDelegate: UIResponder, UIApplicationDelegate, URLSessionDelegate, URLSessionTaskDelegate {
var window: UIWindow?
var uploadTimer: Timer?
var backgroundSession: URLSession?
// Method to upload data to S3 (No need for a file path)
@objc func uploadDataToS3() {
// Use your existing function to fetch and upload the health data
HealthStoreManager.shared.fetchAndUploadHealthData { success in
if success {
print("Data uploaded successfully!")
} else {
print("Failed to upload data.")
}
}
}
func scheduleDailyUpload() {
let calendar = Calendar.current
let currentTime = Date()
var nextUploadTime = calendar.date(bySettingHour: 14, minute: 07, second: 0, of: currentTime)
if let nextTime = nextUploadTime, nextTime < currentTime {
nextUploadTime = calendar.date(byAdding: .day, value: 1, to: nextTime)
}
if let nextUploadTime = nextUploadTime {
let timeInterval = nextUploadTime.timeIntervalSince(currentTime)
uploadTimer = Timer.scheduledTimer(timeInterval: timeInterval, target: self, selector: #selector(uploadDataToS3), userInfo: nil, repeats: true)
}
}
// When the app is launched, schedule the task
func applicationDidBecomeActive(_ application: UIApplication) {
scheduleDailyUpload()
}
// Handle when the app is sent to the background
func applicationDidEnterBackground(_ application: UIApplication) {
// In background, create a background session to handle upload task
let config = URLSessionConfiguration.background(withIdentifier: "com.yourApp.backgroundUpload")
backgroundSession = URLSession(configuration: config, delegate: self, delegateQueue: nil)
// We don't need a file path, so we just trigger your upload function
uploadDataToS3()
}
// Handle when the app comes back to the foreground
func applicationWillEnterForeground(_ application: UIApplication) {
scheduleDailyUpload()
}
// Handle background upload completion or failure
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
if let error = error {
print("Background upload failed with error: \(error.localizedDescription)")
} else {
print("Background upload completed successfully.")
}
}
// Handle the upload progress (optional)
private func urlSession(_ session: URLSession, uploadTask: URLSessionUploadTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
print("Upload progress: \(totalBytesSent) / \(totalBytesExpectedToSend) bytes sent.")
}
// This method is called when the app is terminated and a background upload task is still running
func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
backgroundSession?.getTasksWithCompletionHandler { (_, _, uploadTasks) in
if uploadTasks.count == 0 {
completionHandler() // When the upload task is done, call the completion handler
}
}
}
}
< /code>
Теперь это работает так, как задумано при подключении к XCode в режиме отладки. Он загружает файл автоматически в указанное время, даже когда приложение минимизировано и на заднем плане. Но как только я убиваю отладчика, приложение перестает загружать файл с фона.>
Подробнее здесь: https://stackoverflow.com/questions/794 ... sconnected
NSURLSession работает так, как предполагалось при отладке, но не при отключении ⇐ IOS
Программируем под IOS
1739512476
Anonymous
Это мой код NSURLSession, по сути, я пытаюсь загрузить файл в S3, используя HealthKit в расписании в фоновом режиме. Я просто хочу установить приложение, и этот процесс загрузки должен происходить в графике ежедневно, даже если приложение находится в фоновом режиме. < /P>
import UIKit
class AppDelegate: UIResponder, UIApplicationDelegate, URLSessionDelegate, URLSessionTaskDelegate {
var window: UIWindow?
var uploadTimer: Timer?
var backgroundSession: URLSession?
// Method to upload data to S3 (No need for a file path)
@objc func uploadDataToS3() {
// Use your existing function to fetch and upload the health data
HealthStoreManager.shared.fetchAndUploadHealthData { success in
if success {
print("Data uploaded successfully!")
} else {
print("Failed to upload data.")
}
}
}
func scheduleDailyUpload() {
let calendar = Calendar.current
let currentTime = Date()
var nextUploadTime = calendar.date(bySettingHour: 14, minute: 07, second: 0, of: currentTime)
if let nextTime = nextUploadTime, nextTime < currentTime {
nextUploadTime = calendar.date(byAdding: .day, value: 1, to: nextTime)
}
if let nextUploadTime = nextUploadTime {
let timeInterval = nextUploadTime.timeIntervalSince(currentTime)
uploadTimer = Timer.scheduledTimer(timeInterval: timeInterval, target: self, selector: #selector(uploadDataToS3), userInfo: nil, repeats: true)
}
}
// When the app is launched, schedule the task
func applicationDidBecomeActive(_ application: UIApplication) {
scheduleDailyUpload()
}
// Handle when the app is sent to the background
func applicationDidEnterBackground(_ application: UIApplication) {
// In background, create a background session to handle upload task
let config = URLSessionConfiguration.background(withIdentifier: "com.yourApp.backgroundUpload")
backgroundSession = URLSession(configuration: config, delegate: self, delegateQueue: nil)
// We don't need a file path, so we just trigger your upload function
uploadDataToS3()
}
// Handle when the app comes back to the foreground
func applicationWillEnterForeground(_ application: UIApplication) {
scheduleDailyUpload()
}
// Handle background upload completion or failure
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
if let error = error {
print("Background upload failed with error: \(error.localizedDescription)")
} else {
print("Background upload completed successfully.")
}
}
// Handle the upload progress (optional)
private func urlSession(_ session: URLSession, uploadTask: URLSessionUploadTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
print("Upload progress: \(totalBytesSent) / \(totalBytesExpectedToSend) bytes sent.")
}
// This method is called when the app is terminated and a background upload task is still running
func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
backgroundSession?.getTasksWithCompletionHandler { (_, _, uploadTasks) in
if uploadTasks.count == 0 {
completionHandler() // When the upload task is done, call the completion handler
}
}
}
}
< /code>
Теперь это работает так, как задумано при подключении к XCode в режиме отладки. Он загружает файл автоматически в указанное время, даже когда приложение минимизировано и на заднем плане. Но как только я убиваю отладчика, приложение перестает загружать файл с фона.>
Подробнее здесь: [url]https://stackoverflow.com/questions/79438142/nsurlsession-works-as-intended-when-in-debugging-but-not-when-disconnected[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия