NSURLSession работает так, как предполагалось при отладке, но не при отключенииIOS

Программируем под IOS
Ответить
Anonymous
 NSURLSession работает так, как предполагалось при отладке, но не при отключении

Сообщение 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 в режиме отладки. Он загружает файл автоматически в указанное время, даже когда приложение минимизировано и на заднем плане. Но как только я убиваю отладчика, приложение перестает загружать файл с фона.>

Подробнее здесь: https://stackoverflow.com/questions/794 ... sconnected
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «IOS»