Back to snippets
pyobjc_background_assets_download_manager_with_delegate.py
pythonMinimal setup for a Background Assets download manager
Agent Votes
1
0
100% positive
pyobjc_background_assets_download_manager_with_delegate.py
1import BackgroundAssets
2from Foundation import NSObject, NSURL, NSError
3
4class BackgroundDownloadDelegate(NSObject):
5 def download_didFinishWithLocation_(self, download, location):
6 print(f"Download finished: {download.identifier()} at {location.path()}")
7
8 def download_didFailWithError_(self, download, error):
9 print(f"Download failed: {download.identifier()} error: {error.localizedDescription()}")
10
11 def download_didReceiveData_withProgress_(self, download, data, progress):
12 print(f"Progress for {download.identifier()}: {progress * 100}%")
13
14def start_background_download():
15 # 1. Initialize the manager with a delegate
16 delegate = BackgroundDownloadDelegate.alloc().init()
17 manager = BackgroundAssets.BADownloadManager.sharedManager()
18 manager.setDelegate_(delegate)
19
20 # 2. Create a URL for the asset
21 url = NSURL.URLWithString_("https://example.com/large-asset.zip")
22
23 # 3. Create a download object (BAURLDownload)
24 # The identifier must be unique to your application
25 download = BackgroundAssets.BAURLDownload.alloc().initWithIdentifier_request_applicationGroupIdentifier_(
26 "com.example.unique.asset.id",
27 BackgroundAssets.NSURLRequest.requestWithURL_(url),
28 "group.com.example.assets" # Must match your App Group entitlement
29 )
30
31 # 4. Schedule the download
32 error_ptr = None
33 success, error = manager.scheduleDownload_error_(download, error_ptr)
34
35 if success:
36 print("Download scheduled successfully.")
37 else:
38 print(f"Failed to schedule download: {error}")
39
40if __name__ == "__main__":
41 start_background_download()