Dies ist mein NsurlSession -Code. Im Wesentlichen versuche ich, eine Datei in S3 mit HealthKit nach einem Zeitplan im Hintergrund hochzuladen. Ich möchte nur die App installieren, und dieser Upload -Vorgang sollte täglich automatisch täglich erfolgen, selbst wenn sich die App im Hintergrund befindet. < /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>
Jetzt funktioniert dies wie beabsichtigt, wenn sie im Debugging -Modus mit Xcode verbunden sind. Es lädt die Datei automatisch zum angegebenen Zeitpunkt hoch, auch wenn die App minimiert ist und im Hintergrund. Sobald ich den Debugger töte, lädt die App die Datei nicht mehr aus dem Hintergrund hoch.>
NsurlSession funktioniert wie beim Debuggen wie beabsichtigt, jedoch nicht, wenn es getrennt ist ⇐ IOS
-
- Similar Topics
- Replies
- Views
- Last post
-
-
Beim Versuch, JPA mit Eclipse zu verwenden, wird mein USB automatisch getrennt
by Anonymous » » in Java - 0 Replies
- 5 Views
-
Last post by Anonymous
-