Swift is a powerful and intuitive programming language for Apple platforms and beyond.

Posts under Swift tag

200 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

Failed to produce diagnostic for expression; please submit a bug report
I got the error and I don’t how can I fix it help please struct MovieDetail: View { var movie: Movie let screen = UIScreen.main.bounds @State private var showSeasonPicker = true @State private var selectedSeason = 0 var body: some View { ZStack { Color.black .ignoresSafeArea() ZStack { VStack { HStack { Spacer() Button() { // Closing Button }label: { Image(systemName: "xmark.circle") .font(.system(size: 28)) } } .padding(.horizontal, 22) ScrollView (.vertical, showsIndicators: false){ VStack { StandardHomeMovie(movie: movie) .frame(width: screen.width / 2.5) MovieInfoSubheadline(movie: movie) if movie.promotionHeadline != nil { Text(movie.promotionHeadline!) .bold() .font(.headline) } PlayButton(text: "Play", imagename: "play.fill", backgroundColor: .red) { // } CurrentEpisodeInformation(movie: movie) CastInfo(movie: movie) HStack(spacing: 60){ SmallVerticalButton(text: "My List", isOnImage: "checkmark", isOffImage: "plus", isOn: true) { // } SmallVerticalButton(text: "Rate", isOnImage: "hand.thumbsup.fill", isOffImage: "hand.thumbsup", isOn: true) { // } SmallVerticalButton(text: "Share", isOnImage: "square.and.arrow.up", isOffImage: "square.and.arrow.up", isOn: true) { // } Spacer() } .padding(.leading, 20) CustomTabSwitcher(tabs: [.episodes, .trailers, .more], movie: movie, showSeasonPicker: $showSeasonPicker, selectedSeason: $selectedSeason) } .padding(.horizontal, 10) } Spacer() } .foregroundStyle(.white) if showSeasonPicker { Group { Color.black.opacity(0.9) VStack(spacing: 40){ Spacer() ForEach(0..<(movie.numberOfSeasons ?? 0)) { season in Button(action: { self.selectedSeason = (season != 0) self.showSeasonPicker = false }, label: { Text("Season: \(season + 1)") .foregroundStyle(selectedSeason == season + 1 ? .white : .gray) .bold() .font(.title2) }) } Spacer() Button(action: { self.showSeasonPicker = false }, label: { Image(systemName: "xmark.circle.fill") .foregroundStyle(.white) .font(.system(size: 40)) .scaleEffect(x: 1.1) }) .padding(.bottom, 30) } } .ignoresSafeArea() } } } } } #Preview { MovieDetail(movie: exampleMovie2) } struct MovieInfoSubheadline: View { var movie: Movie var body: some View { HStack(spacing: 20){ Image(systemName: "hand.thumbsup.fill") .foregroundStyle(.white) Text(String(movie.year)) RatingView(rating: movie.rating) Text(movie.numberOfSeasonsDisplay) ZStack{ Text("HD") .foregroundStyle(.white) .font(.system(size: 12)) .bold() Rectangle() .stroke(.gray, lineWidth: 2) .frame(width: 30, height: 20) } } .foregroundStyle(.gray) .padding(.vertical, 6) } } struct RatingView: View { var rating: String var body: some View { ZStack { Rectangle() .foregroundStyle(.gray) Text(rating) .foregroundStyle(.white) .font(.system(size: 12)) .bold() } .frame(width: 50, height: 20) } } struct CastInfo: View { var movie: Movie var body: some View { VStack(spacing: 3) { HStack { Text("Cast: \(movie.cast)") Spacer() } HStack { Text("Creaters: \(movie.creaters)") Spacer() } } .font(.caption) .foregroundStyle(.gray) .padding(.vertical, 10) } } struct CurrentEpisodeInformation: View { var movie: Movie var body: some View { Group { HStack { Text(movie.episodeInfoDisplay) .bold() Spacer() } .padding(.vertical, 4) HStack { Text(movie.episodeDescriptionDisplay) .font(.subheadline) Spacer() } } } }
2
0
55
13h
Problem with NavigationLink
I am making application where I use navigation link to navigate from bottom menu to other views, and there is a problem when I change view a few times because views start stacking and when I set navigationBarBackButtonHidden(false) I can see on left side a lot of back button. This generate big problem because after changing views I got warning Abnormal number of gesture recognizer dependencies: 100. System performance may be affected. Please investigate reducing gesture recognizers and/or their dependencies. And after some more changes everything from screen is pushed down back button. Is there any solution to close previous view from we came? There is code: // // BottomMenu.swift // SpaceManager // // Created by Kuba Kromomołowski on 04/05/2024. // import SwiftUI import Firebase import FirebaseAuth struct BottomMenu: View { @StateObject var logManager = MainViewModel() @StateObject var mvm = MenuViewModel() @State var condition1: Bool = true @State var condition2: Bool = false @State var condition3: Bool = false // @StateObject private var cameraViewModel = CameraViewModel() var body: some View { HStack{ Group{ //.navigationBarBackButtonHidden(true) Spacer() BtnMenu(btnText: "Dodaj", btnIcon: "plus.app.fill", destinationView:AnyView(LoggedMainView()), isActive: condition1 ) Spacer() BtnMenu(btnText: "Szukaj", btnIcon: "magnifyingglass", destinationView:AnyView(SearchView()), isActive: condition2 ) Spacer() BtnMenu(btnText: "Profil", btnIcon: "person.crop.circle.fill", destinationView:AnyView(ProfileView()), isActive: condition3 ) Spacer() }.padding(.bottom, 30) .font(.system(size: 20)) } } } #Preview { BottomMenu() } // // BtnMenu.swift // SpaceManager // // Created by Kuba Kromomołowski on 04/05/2024. // import SwiftUI struct BtnMenu: View { var btnText: String var btnIcon: String var destinationView: AnyView @State var isActive: Bool = true var body: some View { NavigationLink{ destinationView } label: { ZStack { Text("\(Image(systemName: btnIcon)) \(btnText)") } }.disabled(isActive) } }
1
0
62
11h
Assertion failure during deinit due to... DispatchSourceTimer?
I have var idleScanTimer = DispatchSource.makeTimerSource() as a class ivar. When the object is started, I have self.idleScanTimer.schedule(deadline: .now(), repeating: Double(5.0*60)) (and it sets an event handler, that checks some times.) When the object is stopped, it calls self.idleScanTimer.cancel(). At some point, the object containing it is deallocated, and ... sometimes, I think, not always, it crashes: Crashed Thread: 61 Dispatch queue: NEFlow queue [...] Application Specific Information: BUG IN CLIENT OF LIBDISPATCH: Release of an inactive object [...] Thread 61 Crashed:: Dispatch queue: NEFlow queue 0 libdispatch.dylib 0x7ff81c1232cd _dispatch_queue_xref_dispose.cold.2 + 24 1 libdispatch.dylib 0x7ff81c0f84f6 _dispatch_queue_xref_dispose + 55 2 libdispatch.dylib 0x7ff81c0f2dec -[OS_dispatch_source _xref_dispose] + 17 3 com.kithrup.simpleprovider 0x101df5fa7 MyClass.deinit + 87 4 com.kithrup.simpleprovider 0x101dfbdbb MyClass.__deallocating_deinit + 11 5 libswiftCore.dylib 0x7ff829a63460 _swift_release_dealloc + 16 6 com.kithrup.simpleprovider 0x101e122f4 0x101de7000 + 176884 7 libswiftCore.dylib 0x7ff829a63460 _swift_release_dealloc + 16 8 libsystem_blocks.dylib 0x7ff81bfdc654 _Block_release + 130 9 libsystem_blocks.dylib 0x7ff81bfdc654 _Block_release + 130 10 libdispatch.dylib 0x7ff81c0f3317 _dispatch_client_callout + 8 11 libdispatch.dylib 0x7ff81c0f9317 _dispatch_lane_serial_drain + 672 12 libdispatch.dylib 0x7ff81c0f9dfd _dispatch_lane_invoke + 366 13 libdispatch.dylib 0x7ff81c103eee _dispatch_workloop_worker_thread + 753 14 libsystem_pthread.dylib 0x7ff81c2a7fd0 _pthread_wqthread + 326 15 libsystem_pthread.dylib 0x7ff81c2a6f57 start_wqthread + 15 I tried changing it to an optional and having the deinit call .cancel() and set it to nil, but it still crashes. I can't figure out how to get it deallocated in a small, standalone test program.
2
0
51
5m
Use of SceneDelegate not working
I am trying to configure scenes to capture a redirect URL after a successful login attempt. I am using OAuth code flow. This is the code I have so far: ios_app.swift import SwiftUI @main struct ios_appApp: App { @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate let persistenceController = PersistenceController.shared @StateObject private var authState = AuthState() var body: some Scene { WindowGroup { ContentView() .environment(\.managedObjectContext, persistenceController.container.viewContext) .environmentObject(authState) } } } AppDelegate.swift import UIKit import AWSMobileClient import GoogleSignIn class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { print("AppDelegate: didFinishLaunchingWithOptions") AWSMobileClient.default().initialize { (userState, error) in if let userState = userState { print("UserState: \(userState)") } else if let error = error { print("Error initializing AWSMobileClient: \(error.localizedDescription)") } } GIDSignIn.sharedInstance.restorePreviousSignIn { user, error in if let error = error { print("Error restoring previous Google Sign-In: \(error.localizedDescription)") } } return true } } SceneDelegate.swift import UIKit import SwiftUI import GoogleSignIn class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { print("SceneDelegate: scene willConnectTo") guard let windowScene = (scene as? UIWindowScene) else { print("SceneDelegate: Invalid windowScene") return } let window = UIWindow(windowScene: windowScene) let contentView = ContentView().environmentObject(AuthState()) window.rootViewController = UIHostingController(rootView: contentView) self.window = window window.makeKeyAndVisible() print("SceneDelegate: window initialized and visible") } func sceneDidDisconnect(_ scene: UIScene) { print("SceneDelegate: sceneDidDisconnect") } func sceneDidBecomeActive(_ scene: UIScene) { print("SceneDelegate: sceneDidBecomeActive") } func sceneWillResignActive(_ scene: UIScene) { print("SceneDelegate: sceneWillResignActive") } func sceneWillEnterForeground(_ scene: UIScene) { print("SceneDelegate: sceneWillEnterForeground") } func sceneDidEnterBackground(_ scene: UIScene) { print("SceneDelegate: sceneDidEnterBackground") } func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) { guard let url = URLContexts.first?.url else { print("SceneDelegate: No URL found in URLContexts") return } print("SceneDelegate: openURLContexts with URL: \(url)") if GIDSignIn.sharedInstance.handle(url) { print("SceneDelegate: Google Sign-In handled URL") return } if url.scheme == "myurlscheme" || (url.scheme == "https" && url.host == "mydomain.com" && url.path == "/mobile-auth-callback") { print("SceneDelegate: Handling auth response for URL: \(url)") AuthService.shared.handleOAuthCallback(url: url) } else { print("SceneDelegate: URL scheme not handled: \(url.scheme ?? "No scheme")") } } func scene(_ scene: UIScene, continue userActivity: NSUserActivity) { print("SceneDelegate: continue userActivity") if userActivity.activityType == NSUserActivityTypeBrowsingWeb { if let url = userActivity.webpageURL { handleUniversalLink(url: url) } } } private func handleUniversalLink(url: URL) { print("SceneDelegate: Handling universal link: \(url)") if url.path.contains("/mobile-auth-callback") { let queryItems = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems let code = queryItems?.first(where: { $0.name == "code" })?.value if let code = code { print("SceneDelegate: Received code: \(code)") AuthService.shared.exchangeCodeForToken(code: code) } else { print("SceneDelegate: No code found, handling email/password callback") AuthService.shared.handleEmailPasswordCallback(url: url) } } } } Also introduced this configuration in Info.plist: <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>UIApplicationSceneManifest</key> <dict> <key>UIApplicationSupportsMultipleScenes</key> <true/> <key>UISceneConfigurations</key> <dict> <key>UIWindowSceneSessionRoleApplication</key> <array> <dict> <key>UISceneConfigurationName</key> <string>Default Configuration</string> <key>UISceneDelegateClassName</key> <string>ios-app.SceneDelegate</string> </dict> </array> </dict> </dict> ...Other parameters </dict> </plist> I am using the simulator to launch my app and can see AppDelegate related logs but I am not seeing any SceneDelegate logs (I suppose because it is not being initialized nor called). I have tried restarting the computer/Xcode, clean and rebuild the application but none of the things I tested work. Is there any part of my code wrong? Any other idea here?
0
0
33
17h
MultivariateLinearRegressor problem training
Hi everyone, I attempted to use the MultivariateLinearRegressor from the Create ML Components framework to fit some multi-dimensional data linearly (4 dimensions in my example). I aim to obtain multi-dimensional output points (2 points in my example). However, when I fit the model with my training data and test it, it appears that only the first element of my training data is used for training, regardless of whether I use CreateMLComponents.AnnotatedBatch or [CreateMLComponents.AnnotatedFeature, CoreML.MLShapedArray>] as input. let sourceMatrix: [[Double]] = [ [0,0.1,0.2,0.3], [0.5,0.2,0.6,0.2] ] let referenceMatrix: [[Double]] = [ [0.2,0.7], [0.9,0.1] ] Here is a test code to test the function (ios 18.0 beta, Xcode 16.0 beta) In this example I train the model to learn 2 multidimensional points (4 dimensions) and here are the results of the predictions: ▿ 2 elements ▿ 0 : AnnotatedPrediction<MLShapedArray<Double>, MLShapedArray<Double>> ▿ prediction : 0.20000000298023224 0.699999988079071 ▿ _storage : <StandardStorage<Double>: 0x600002ad8270> ▿ annotation : 0.2 0.7 ▿ _storage : <StandardStorage<Double>: 0x600002b30600> ▿ 1 : AnnotatedPrediction<MLShapedArray<Double>, MLShapedArray<Double>> ▿ prediction : 0.23158159852027893 0.9509953260421753 ▿ _storage : <StandardStorage<Double>: 0x600002ad8c90> ▿ annotation : 0.9 0.1 ▿ _storage : <StandardStorage<Double>: 0x600002b55f20> 0.23158159852027893 0.9509953260421753 is totally random and should be far more closer to [0.9,0.1]. Here is the test code : ( i run it on "My mac, Designed for Ipad") ContentView.swift import CoreImage import CoreImage.CIFilterBuiltins import UIKit import CoreGraphics import Accelerate import Foundation import CoreML import CreateML import CreateMLComponents func createMLShapedArray(from array: [Double], shape: [Int]) -> MLShapedArray<Double> { return MLShapedArray<Double>(scalars: array, shape: shape) } func calculateTransformationMatrixWithNonlinearity(sourceRGB: [[Double]], referenceRGB: [[Double]], degree: Int = 3) async throws -> MultivariateLinearRegressor<Double>.Model { let annotatedFeatures2 = zip(sourceRGB, referenceRGB).map { (featureArray, targetArray) -> AnnotatedFeature<MLShapedArray<Double>, MLShapedArray<Double>> in let featureMLShapedArray = createMLShapedArray(from: featureArray, shape: [featureArray.count]) let targetMLShapedArray = createMLShapedArray(from: targetArray, shape: [targetArray.count]) return AnnotatedFeature(feature: featureMLShapedArray, annotation: targetMLShapedArray) } // Flatten the sourceRGBPoly into a single-dimensional array var flattenedArray = sourceRGB.flatMap { $0 } let featuresMLShapedArray = createMLShapedArray(from: flattenedArray, shape: [2, 4]) flattenedArray = referenceRGB.flatMap { $0 } let targetMLShapedArray = createMLShapedArray(from: flattenedArray, shape: [2, 2]) // Create AnnotatedFeature instances /* let annotatedFeatures2: [AnnotatedFeature<MLShapedArray<Double>, MLShapedArray<Double>>] = [ AnnotatedFeature(feature: featuresMLShapedArray, annotation: targetMLShapedArray) ]*/ let annotatedBatch = AnnotatedBatch(features: featuresMLShapedArray, annotations: targetMLShapedArray) var regressor = MultivariateLinearRegressor<Double>() regressor.configuration.learningRate = 0.1 regressor.configuration.maximumIterationCount=5000 regressor.configuration.batchSize=2 let model = try await regressor.fitted(to: annotatedBatch,validateOn: nil) //var model = try await regressor.fitted(to: annotatedFeatures2) // Proceed to prediction once the model is fitted let predictions = try await model.prediction(from: annotatedFeatures2) // Process or use the predictions print(predictions) print("Predictions:", predictions) return model } struct ContentView: View { var body: some View { VStack {} .onAppear { Task { do { let sourceMatrix: [[Double]] = [ [0,0.1,0.2,0.3], [0.5,0.2,0.6,0.2] ] let referenceMatrix: [[Double]] = [ [0.2,0.7], [0.9,0.1] ] let model = try await calculateTransformationMatrixWithNonlinearity(sourceRGB: sourceMatrix, referenceRGB: referenceMatrix, degree: 2 ) print("Model fitted successfully:", model) } catch { print("Error:", error) } } } } }
2
0
64
14h
ViewDidLoad in SwiftUI
Hello. I want to do a fetch when a view loads. In UIKit I would have used viewDidLoad to do this but in SwiftUI we only have onAppear and task. Is that by design, and if so, what is the recommended way to fetch data? I wrote a little blog post for a workaround describing the issue and the found solution, but I presume there is a better way. https://www.ludafux.com/post/viewdidload_doppelganger Best Regards, Luda
4
0
49
10h
Multiple async lets crash the app
Usage of multiple async lets crashes the app in a nondeterministic fashion. We are experiencing this crash in production, but it is rare. 0 libswift_Concurrency.dylib 0x20a8b89b4 swift_task_create_commonImpl(unsigned long, swift::TaskOptionRecord*, swift::TargetMetadata<swift::InProcess> const*, void (swift::AsyncContext* swift_async_context) swiftasynccall*, void*, unsigned long) + 384 1 libswift_Concurrency.dylib 0x20a8b6970 swift_asyncLet_begin + 36 We managed to isolate the issue, and we submitted a technical incident (Case-ID: 8007727). However, we were completely ignored, and referred to the developer forums. To reproduce the bug you need to run the code on a physical device and under instruments (we used swift concurrency). This bug is present on iOS 17 and 18, Xcode 15.1, 15.4 and 16 beta, swift 5 and 6, including strict concurrency. Here's the code for Swift 6 / Xcode 16 / strict concurrency: (I wanted to attach the project but for some reason I am unable to) typealias VoidHandler = () -> Void enum Fetching { case inProgress, idle } protocol PersonProviding: Sendable { func getPerson() async throws -> Person } actor PersonProvider: PersonProviding { func getPerson() async throws -> Person { async let first = getFirstName() async let last = getLastName() async let age = getAge() async let role = getRole() return try await Person(firstName: first, lastName: last, age: age, familyMemberRole: role) } private func getFirstName() async throws -> String { try await Task.sleep(nanoseconds: 1_000_000_000) return ["John", "Kate", "Alex"].randomElement()! } private func getLastName() async throws -> String { try await Task.sleep(nanoseconds: 1_400_000_000) return ["Kowalski", "McMurphy", "Grimm"].randomElement()! } private func getAge() async throws -> Int { try await Task.sleep(nanoseconds: 2_100_000_000) return [56, 24, 11].randomElement()! } private func getRole() async throws -> Person.Role { try await Task.sleep(nanoseconds: 500_000_000) return Person.Role.allCases.randomElement()! } } @MainActor final class ViewModel { private let provider: PersonProviding = PersonProvider() private var fetchingTask: Task<Void, Never>? let onFetchingChanged: (Fetching) -> Void let onPersonFetched: (Person) -> Void init(onFetchingChanged: @escaping (Fetching) -> Void, onPersonFetched: @escaping (Person) -> Void) { self.onFetchingChanged = onFetchingChanged self.onPersonFetched = onPersonFetched } func fetchData() { fetchingTask?.cancel() fetchingTask = Task { do { onFetchingChanged(.inProgress) let person = try await provider.getPerson() guard !Task.isCancelled else { return } onPersonFetched(person) onFetchingChanged(.idle) } catch { print(error) } } } } struct Person { enum Role: String, CaseIterable { case mum, dad, brother, sister } let firstName: String let lastName: String let age: Int let familyMemberRole: Role init(firstName: String, lastName: String, age: Int, familyMemberRole: Person.Role) { self.firstName = firstName self.lastName = lastName self.age = age self.familyMemberRole = familyMemberRole } } import UIKit class ViewController: UIViewController { @IBOutlet private var first: UILabel! @IBOutlet private var last: UILabel! @IBOutlet private var age: UILabel! @IBOutlet private var role: UILabel! @IBOutlet private var spinner: UIActivityIndicatorView! private lazy var viewModel = ViewModel(onFetchingChanged: { [weak self] state in switch state { case .idle: self?.spinner.stopAnimating() case .inProgress: self?.spinner.startAnimating() } }, onPersonFetched: { [weak self] person in guard let self else { return } first.text = person.firstName last.text = person.lastName age.text = "\(person.age)" role.text = person.familyMemberRole.rawValue }) @IBAction private func onTap() { viewModel.fetchData() } }
0
0
39
19h
Issue while accessing file from another PC on local network using document picker with SMB.
We are trying to access and copy some files [e.g., video file] from another PC on local network using SMB protocol. We found some third party libraries like AMSMB2 for this.  But we want to try to use Apple inbuilt features like File management mentioned in - https://developer.apple.com/videos/play/wwdc2019/719/ We could able to select file from SMB server using document picker in app manually. Also we got its url in debug which gets generated under "Shared" section in files app. The URL I get from document picker is -> /private/var/mobile/Library/LiveFiles/com.apple.filesystems.smbclientd/asd0QUsers/testuser/iOS/SMB_ShareFolder Now we want to avoid manual selection of file to user.We want directly open "/private/var/mobile/Library/LiveFiles/com.apple.filesystems.smbclientd/asd0QUsers/testuser/iOS/SMB_ShareFolder" path as soon as document picker opens. So that user can directly select file. But it is not working. It opens normal files app and all folders. Getting below error -  Access Shared URL directly using documentPicker "Error - CFURLResourceIsReachable failed because it was passed a URL which has no scheme" Sharing the code which I tried to open this shared folder directly :  let url = URL (string: "/private/var/mobile/Library/LiveFiles/com.apple.filesystems.smbclientd/asd0QUsers/Pranjali/iOS/SMB_ShareFolder")  let documentPicker = UIDocumentPickerViewController(forOpeningContentTypes: [UTType.folder])     documentPicker.delegate = self     documentPicker.allowsMultipleSelection = false     documentPicker.modalPresentationStyle = .custom     documentPicker.definesPresentationContext = true     documentPicker.directoryURL = url!       documentPicker.transitioningDelegate = customTransitioningDelegate    present(documentPicker, animated: true, completion: nil) I get error in console - CFURLResourceIsReachable failed because it was passed a URL which has no scheme 2024-07-05 17:49:38.501059+0530 VideoImportPOC[1327:336989] [DocumentManager] revealDocumentAtURL encountered an error: Error Domain=NSCocoaErrorDomain Code=262 "The file couldn’t be opened because the specified URL type isn’t supported." Can you please provide inputs if it is possible to access files directly in this way? or any other suggestions.
1
0
64
23h
Can I block certain iPhone types from using my app?
I have been working on an app, and am really happy with the designs on iPhones 15-11, however every time I use the iPhone SE, the designs look terrible and everything overlaps (yes even with restraints and stack views and what not.) I want to know could I make a seperate version of my app for every iPhone (that isn't the se) and a special dedicated version for SE users? If this isn't possible, can I just block SE users from the app?
2
0
64
12h
Failed to build the scheme "project name"
Hello, Developer team! Does anyone have an idea about the problem I'm facing with the simulator ? I'm learning how to code in SwiftUI and my simulator was working just fine but yesterday I close my laptop the other day and open today and see the code : import SwiftUI import SwiftData @main struct first_projectApp: App { var sharedModelContainer: ModelContainer = { let schema = Schema([ Item.self, ]) let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false) do { return try ModelContainer(for: schema, configurations: [modelConfiguration]) } catch { fatalError("Could not create ModelContainer: \(error)") } }() var body: some Scene { WindowGroup { ContentView() } .modelContainer(sharedModelContainer) } } I don't know where it comes from . I used IOS 17.5 I try to upgrade to IOS 18 but that didn't fix the problem. Currently I'm seeing 3 errors : Showing Recent Errors Only Build target first project of project first project with configuration Debug Ld /Users/amedekatamatode/Library/Developer/Xcode/DerivedData/first_project-ebsglpjmgwtgzpflkvloohzydjuf/Build/Products/Debug-iphonesimulator/first\ project.app/first\ project.debug.dylib normal (in target 'first project' from project 'first project') cd /Users/amedekatamatode/Desktop/calculator/first\ project /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -Xlinker -reproducible -target arm64-apple-ios17.5-simulator -dynamiclib -isysroot /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator18.0.sdk -O0 -L/Users/amedekatamatode/Library/Developer/Xcode/DerivedData/first_project-ebsglpjmgwtgzpflkvloohzydjuf/Build/Intermediates.noindex/EagerLinkingTBDs/Debug-iphonesimulator -L/Users/amedekatamatode/Library/Developer/Xcode/DerivedData/first_project-ebsglpjmgwtgzpflkvloohzydjuf/Build/Products/Debug-iphonesimulator -F/Users/amedekatamatode/Library/Developer/Xcode/DerivedData/first_project-ebsglpjmgwtgzpflkvloohzydjuf/Build/Intermediates.noindex/EagerLinkingTBDs/Debug-iphonesimulator -F/Users/amedekatamatode/Library/Developer/Xcode/DerivedData/first_project-ebsglpjmgwtgzpflkvloohzydjuf/Build/Products/Debug-iphonesimulator -filelist /Users/amedekatamatode/Library/Developer/Xcode/DerivedData/first_project-ebsglpjmgwtgzpflkvloohzydjuf/Build/Intermediates.noindex/first\ project.build/Debug-iphonesimulator/first\ project.build/Objects-normal/arm64/first\ project.LinkFileList -install_name @rpath/first\ project.debug.dylib -Xlinker -rpath -Xlinker @executable_path/Frameworks -dead_strip -Xlinker -object_path_lto -Xlinker /Users/amedekatamatode/Library/Developer/Xcode/DerivedData/first_project-ebsglpjmgwtgzpflkvloohzydjuf/Build/Intermediates.noindex/first\ project.build/Debug-iphonesimulator/first\ project.build/Objects-normal/arm64/first\ project_lto.o -Xlinker -export_dynamic -Xlinker -no_deduplicate -Xlinker -objc_abi_version -Xlinker 2 -Xlinker -debug_variant -fobjc-link-runtime -fprofile-instr-generate -L/Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/iphonesimulator -L/usr/lib/swift -Xlinker -add_ast_path -Xlinker /Users/amedekatamatode/Library/Developer/Xcode/DerivedData/first_project-ebsglpjmgwtgzpflkvloohzydjuf/Build/Intermediates.noindex/first\ project.build/Debug-iphonesimulator/first\ project.build/Objects-normal/arm64/first_project.swiftmodule -Xlinker -alias -Xlinker _main -Xlinker ___debug_main_executable_dylib_entry_point -Xlinker -no_adhoc_codesign -Xlinker -dependency_info -Xlinker /Users/amedekatamatode/Library/Developer/Xcode/DerivedData/first_project-ebsglpjmgwtgzpflkvloohzydjuf/Build/Intermediates.noindex/first\ project.build/Debug-iphonesimulator/first\ project.build/Objects-normal/arm64/first\ project_dependency_info.dat -o /Users/amedekatamatode/Library/Developer/Xcode/DerivedData/first_project-ebsglpjmgwtgzpflkvloohzydjuf/Build/Products/Debug-iphonesimulator/first\ project.app/first\ project.debug.dylib ld: warning: Could not parse or use implicit file '/Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/System/Library/Frameworks/SwiftUICore.framework/SwiftUICore.tbd': cannot link directly with 'SwiftUICore' because product being built is not an allowed client of it Undefined symbols for architecture arm64: "_main", referenced from: ___debug_main_executable_dylib_entry_point in command-line-aliases-file ld: symbol(s) not found for architecture arm64 clang: error: linker command failed with exit code 1 (use -v to see invocation) Undefined symbol: _main Linker command failed with exit code 1 (use -v to see invocation) I hope someone helps me how to figure it out. Thank you!
0
0
90
2d
LOCALIZED_STRING_MACRO_NAMES for Swift package targets?
I have a custom localisation function in my project that enforces the inclusion of the bundle parameter (specifically so that Swift packages are forced to include the Bundle.module value). While migrating to String Catalogs, I noticed that my custom localisation function wasn't being recognised by the automatic extraction that the Swift compiler is doing, but only in my Swift package targets. Is there a way to set something like LOCALIZED_STRING_MACRO_NAMES in Swift Packages?
1
0
143
3d
SwiftData custom migration crash
Starting point I have an app that is in production that has a single entity called CDShift. This is the class: @Model final class CDShift { var identifier: UUID = UUID() var date: Date = Date() ... } This is how this model is written in the current version. Where I need to go Now, I'm updating the app and I have to do some modifications, that are: add a new entity, called DayPlan add the relationship between DayPlan and CDShift What I did is this: enum SchemaV1: VersionedSchema { static var versionIdentifier = Schema.Version(1, 0, 0) static var models: [any PersistentModel.Type] { [CDShift.self] } @Model final class CDShift { var identifier: UUID = UUID() var date: Date = Date() } } To encapsulate the current CDShift in a version 1 of the schema. Then I created the version 2: enum SchemaV2: VersionedSchema { static var versionIdentifier = Schema.Version(2, 0, 0) static var models: [any PersistentModel.Type] { [CDShift.self, DayPlan.self] } @Model final class DayPlan { var identifier: UUID = UUID() var date: Date = Date() @Relationship(inverse: \CDShift.dayPlan) var shifts: [CDShift]? = [] } @Model final class CDShift { var identifier: UUID = UUID() var date: Date = Date() var dayPlan: DayPlan? = nil } } The migration plan Finally, I created the migration plan: enum MigrationPlan: SchemaMigrationPlan { static var schemas: [any VersionedSchema.Type] { [SchemaV1.self, SchemaV2.self] } static let migrateV1toV2 = MigrationStage.custom( fromVersion: SchemaV1.self, toVersion: SchemaV2.self) { context in // willMigrate, only access to old models } didMigrate: { context in // didMigrate, only access to new models let shifts = try context.fetch(FetchDescriptor<SchemaV2.CDShift>()) for shift in shifts { let dayPlan = DayPlan(date: shift.date) dayPlan.shifts?.append(shift) context.insert(dayPlan) } } static var stages: [MigrationStage] { print("MigrationPlan | stages called") return [migrateV1toV2] } } The ModelContainer Last, but not least, how the model container is created in the App: struct MyApp: App { private let container: ModelContainer init() { container = ModelContainer.appContainer } var body: some Scene { WindowGroup { ... } .modelContainer(container) } } This is the extension of ModelContainer: extension ModelContainer { static var appContainer: ModelContainer { let schema = Schema([ CDShift.self, DayPlan.self ]) let modelConfiguration = ModelConfiguration( schema: schema, isStoredInMemoryOnly: Ecosystem.current.isPreview, groupContainer: .identifier(Ecosystem.current.appGroupIdentifier) ) do { // let container = try ModelContainer(for: schema, configurations: modelConfiguration) let container = try ModelContainer(for: schema, migrationPlan: MigrationPlan.self, configurations: modelConfiguration) AMLogger.verbose("SwiftData path: \(modelConfiguration.url.path)") return container } catch (let error) { fatalError("Could not create ModelContainer: \(error)") } } } The error This has always worked perfectly until the migration. It crashes on the fatalError line, this is the error: Unable to find a configuration named 'default' in the specified managed object model. Notes It seems that the version of the store is never updated to 2, but it keeps staying on 1. I tried also using the lightweight migration, no crash, it seems it recognizes the new entity, but the store version is always 1. iCloud is enabled I thought that the context used in the custom migration blocks is not the "right" one that I use when I create my container If I use the lightweight migration, everything seems to work fine, but I have to manually do the association between the DayPlan and the CDShift objects Do you have an idea on how to help in this case?
1
0
139
3d
Microphone input in website in webview for swiftui
I have a website of a chatbot that also accepts microphone inputs and I embedded that into my swift and the everything other than the mic is working. I have included permission in the info file and here’s some of the code : import SwiftUI import WebKit import AVFoundation struct WebView: UIViewRepresentable { let url: URL class Coordinator: NSObject, WKUIDelegate, WKNavigationDelegate { var parent: WebView init(parent: WebView) { self.parent = parent } func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { decisionHandler(.allow) } func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) { let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { _ in completionHandler() })) parent.presentAlert(alert: alert) } func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) { let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { _ in completionHandler(true) })) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { _ in completionHandler(false) })) parent.presentAlert(alert: alert) } func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) { let alert = UIAlertController(title: prompt, message: nil, preferredStyle: .alert) alert.addTextField { textField in textField.text = defaultText } alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { _ in completionHandler(alert.textFields?.first?.text) })) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { _ in completionHandler(nil) })) parent.presentAlert(alert: alert) } func webView(_ webView: WKWebView, requestMediaCapturePermissionFor origin: WKSecurityOrigin, initiatedByFrame frame: WKFrameInfo, type: WKMediaCaptureType, decisionHandler: @escaping (WKPermissionDecision) -> Void) { decisionHandler(.grant) } func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { print("Navigation error: \(error.localizedDescription)") } } func makeCoordinator() -> Coordinator { Coordinator(parent: self) } func makeUIView(context: Context) -> WKWebView { let webConfiguration = WKWebViewConfiguration() webConfiguration.allowsInlineMediaPlayback = true webConfiguration.mediaTypesRequiringUserActionForPlayback = [] let webView = WKWebView(frame: .zero, configuration: webConfiguration) webView.uiDelegate = context.coordinator webView.navigationDelegate = context.coordinator requestMicrophoneAccess() return webView } func updateUIView(_ webView: WKWebView, context: Context) { let request = URLRequest(url: url) webView.load(request) } func requestMicrophoneAccess() { AVAudioSession.sharedInstance().requestRecordPermission { granted in DispatchQueue.main.async { if granted { print("Microphone access granted") } else { print("Microphone access denied") } } } } func presentAlert(alert: UIAlertController) { if let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene, let rootViewController = windowScene.windows.first?.rootViewController { rootViewController.present(alert, animated: true, completion: nil) } } }
0
0
110
2d
Microphone input in website in webview for swiftui
I have a website of a chatbot that also accepts microphone inputs and I embedded that into my swift and the everything other than the mic is working. I have included permission in the info file and here's some of the code : import SwiftUI import WebKit import AVFoundation struct WebView: UIViewRepresentable { let url: URL class Coordinator: NSObject, WKUIDelegate, WKNavigationDelegate { var parent: WebView init(parent: WebView) { self.parent = parent } func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { decisionHandler(.allow) } func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) { let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { _ in completionHandler() })) parent.presentAlert(alert: alert) } func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) { let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { _ in completionHandler(true) })) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { _ in completionHandler(false) })) parent.presentAlert(alert: alert) } func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) { let alert = UIAlertController(title: prompt, message: nil, preferredStyle: .alert) alert.addTextField { textField in textField.text = defaultText } alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { _ in completionHandler(alert.textFields?.first?.text) })) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { _ in completionHandler(nil) })) parent.presentAlert(alert: alert) } func webView(_ webView: WKWebView, requestMediaCapturePermissionFor origin: WKSecurityOrigin, initiatedByFrame frame: WKFrameInfo, type: WKMediaCaptureType, decisionHandler: @escaping (WKPermissionDecision) -> Void) { decisionHandler(.grant) } func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { print("Navigation error: \(error.localizedDescription)") } } func makeCoordinator() -> Coordinator { Coordinator(parent: self) } func makeUIView(context: Context) -> WKWebView { let webConfiguration = WKWebViewConfiguration() webConfiguration.allowsInlineMediaPlayback = true webConfiguration.mediaTypesRequiringUserActionForPlayback = [] let webView = WKWebView(frame: .zero, configuration: webConfiguration) webView.uiDelegate = context.coordinator webView.navigationDelegate = context.coordinator requestMicrophoneAccess() return webView } func updateUIView(_ webView: WKWebView, context: Context) { let request = URLRequest(url: url) webView.load(request) } func requestMicrophoneAccess() { AVAudioSession.sharedInstance().requestRecordPermission { granted in DispatchQueue.main.async { if granted { print("Microphone access granted") } else { print("Microphone access denied") } } } } func presentAlert(alert: UIAlertController) { if let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene, let rootViewController = windowScene.windows.first?.rootViewController { rootViewController.present(alert, animated: true, completion: nil) } } }
0
0
85
3d
ContentView
Hello, I‘ve started developing an App not to long ago on Xcode and I have noticed that I can’t see any progress or like preview of what I have coded so far and it’s starting to concern me. I have Xcode version 15.5 and I am coding with swift, everything works fine there is no error or anything preventing it to run but when I try to preview the only thing I see when I launch the Simulator and I open my app the only thing I see is a white page. Can someone please help me.
2
0
123
3d
How to save to specific stores/configurations in Core Data
I'm currently syncing core data with the CloudKit private and public databases, as you can see in the code below, I'm saving the private database in the default configuration in Core Data and the public in a configuration called Public everything works fine when NSPersistentCloudKitContainer syncs, what I'm having an issue with is trying to save to the public data store PublicStore, for instance when I try to save with func createIconImage(imageName: String) it saves the image to the "default" store, not the PublicStore(Public configuration). What could I do to make the createIconImage() function save to the PublicStore sqlite database? class CoreDataManager: ObservableObject{ static let instance = CoreDataManager() private let queue = DispatchQueue(label: "CoreDataManagerQueue") @AppStorage(UserDefaults.Keys.iCloudSyncKey) private var iCloudSync = false lazy var context: NSManagedObjectContext = { return container.viewContext }() lazy var container: NSPersistentContainer = { return setupContainer() }() init(inMemory: Bool = false){ if inMemory { container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null") } } func updateCloudKitContainer() { queue.sync { container = setupContainer() } } private func getDocumentsDirectory() -> URL { return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] } private func getStoreURL(for storeName: String) -> URL { return getDocumentsDirectory().appendingPathComponent("\(storeName).sqlite") } func setupContainer()->NSPersistentContainer{ let container = NSPersistentCloudKitContainer(name: "CoreDataContainer") let cloudKitContainerIdentifier = "iCloud.com.example.MyAppName" guard let description = container.persistentStoreDescriptions.first else{ fatalError("###\(#function): Failed to retrieve a persistent store description.") } description.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey) description.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey) if iCloudSync{ if description.cloudKitContainerOptions == nil { let options = NSPersistentCloudKitContainerOptions(containerIdentifier: cloudKitContainerIdentifier) description.cloudKitContainerOptions = options } }else{ print("Turning iCloud Sync OFF... ") description.cloudKitContainerOptions = nil } // Setup public database let publicDescription = NSPersistentStoreDescription(url: getStoreURL(for: "PublicStore")) publicDescription.configuration = "Public" // this is the configuration name if publicDescription.cloudKitContainerOptions == nil { let publicOptions = NSPersistentCloudKitContainerOptions(containerIdentifier: cloudKitContainerIdentifier) publicOptions.databaseScope = .public publicDescription.cloudKitContainerOptions = publicOptions } container.persistentStoreDescriptions.append(publicDescription) container.loadPersistentStores { (description, error) in if let error = error{ print("Error loading Core Data. \(error)") } } container.viewContext.automaticallyMergesChangesFromParent = true container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy return container } func save(){ do{ try context.save() //print("Saved successfully!") }catch let error{ print("Error saving Core Data. \(error.localizedDescription)") } } } class PublicViewModel: ObservableObject { let manager: CoreDataManager @Published var publicIcons: [PublicServiceIconImage] = [] init(coreDataManager: CoreDataManager = .instance) { self.manager = coreDataManager } func createIconImage(imageName: String) { let newImage = PublicServiceIconImage(context: manager.context) newImage.imageName = imageName newImage.id = UUID() save() } func save() { self.manager.save() } }
1
0
90
19h
Generating Live Photo from JPG and MOV fails
I am working on an iOS application using SwiftUI where I want to convert a JPG and a MOV file to a live photo. I am utilizing the LivePhoto Class from Github for this. The JPG and MOV files are displayed correctly in my WallpaperDetailView, but I am facing issues when trying to download the live photo to the gallery and generate the Live Photo. Here is the relevant code and the errors I am encountering: Console prints: Play button should be visible Image URL fetched and set: Optional("https://firebasestorage.googleapis.com/...") Video is ready to play Video downloaded to: file:///var/mobile/Containers/Data/Application/.../tmp/CFNetworkDownload_7rW5ny.tmp Failed to generate Live Photo I have verified that the app has the necessary permissions to access the Photo Library. The JPEG and MOV files are successfully downloaded and can be displayed in the app. The issue seems to occur when generating the Live Photo from the downloaded files. struct WallpaperDetailView: View { var wallpaper: Wallpaper @State private var isLoading = false @State private var isImageSaved = false @State private var imageURL: URL? @State private var livePhotoVideoURL: URL? @State private var player: AVPlayer? @State private var playerViewController: AVPlayerViewController? @State private var isVideoReady = false @State private var showBuffering = false var body: some View { ZStack { if let imageURL = imageURL { GeometryReader { geometry in KFImage(imageURL) .resizable() ... } } if let playerViewController = playerViewController { VideoPlayerViewController(playerViewController: playerViewController) .frame(maxWidth: .infinity, maxHeight: .infinity) .clipped() .edgesIgnoringSafeArea(.all) } } .onAppear { PHPhotoLibrary.requestAuthorization { status in if status == .authorized { loadImage() } else { print("User denied access to photo library") } } } private func loadImage() { isLoading = true if let imageURLString = wallpaper.imageURL, let imageURL = URL(string: imageURLString) { self.imageURL = imageURL if imageURL.scheme == "file" { self.isLoading = false print("Local image URL set: \(imageURL)") } else { fetchDownloadURL(from: imageURLString) { url in self.imageURL = url self.isLoading = false print("Image URL fetched and set: \(String(describing: url))") } } } if let livePhotoVideoURLString = wallpaper.livePhotoVideoURL, let livePhotoVideoURL = URL(string: livePhotoVideoURLString) { self.livePhotoVideoURL = livePhotoVideoURL preloadAndPlayVideo(from: livePhotoVideoURL) } else { self.isLoading = false print("No valid image or video URL") } } private func preloadAndPlayVideo(from url: URL) { self.player = AVPlayer(url: url) let playerViewController = AVPlayerViewController() playerViewController.player = self.player self.playerViewController = playerViewController let playerItem = AVPlayerItem(url: url) playerItem.preferredForwardBufferDuration = 1.0 self.player?.replaceCurrentItem(with: playerItem) ... print("Live Photo Video URL set: \(url)") } private func saveWallpaperToPhotos() { if let imageURL = imageURL, let livePhotoVideoURL = livePhotoVideoURL { saveLivePhotoToPhotos(imageURL: imageURL, videoURL: livePhotoVideoURL) } else if let imageURL = imageURL { saveImageToPhotos(url: imageURL) } } private func saveImageToPhotos(url: URL) { ... } private func saveLivePhotoToPhotos(imageURL: URL, videoURL: URL) { isLoading = true downloadVideo(from: videoURL) { localVideoURL in guard let localVideoURL = localVideoURL else { print("Failed to download video for Live Photo") DispatchQueue.main.async { self.isLoading = false } return } print("Video downloaded to: \(localVideoURL)") self.generateAndSaveLivePhoto(imageURL: imageURL, videoURL: localVideoURL) } } private func generateAndSaveLivePhoto(imageURL: URL, videoURL: URL) { LivePhoto.generate(from: imageURL, videoURL: videoURL, progress: { percent in print("Progress: \(percent)") }, completion: { livePhoto, resources in guard let resources = resources else { print("Failed to generate Live Photo") DispatchQueue.main.async { self.isLoading = false } return } print("Live Photo generated with resources: \(resources)") self.saveLivePhotoToLibrary(resources: resources) }) } private func saveLivePhotoToLibrary(resources: LivePhoto.LivePhotoResources) { LivePhoto.saveToLibrary(resources) { success in DispatchQueue.main.async { if success { self.isImageSaved = true print("Live Photo saved successfully") } else { print("Failed to save Live Photo") } self.isLoading = false } } } private func fetchDownloadURL(from gsURL: String, completion: @escaping (URL?) -> Void) { let storageRef = Storage.storage().reference(forURL: gsURL) storageRef.downloadURL { url, error in if let error = error { print("Failed to fetch image URL: \(error)") completion(nil) } else { completion(url) } } } private func downloadVideo(from url: URL, completion: @escaping (URL?) -> Void) { let task = URLSession.shared.downloadTask(with: url) { localURL, response, error in guard let localURL = localURL, error == nil else { print("Failed to download video: \(String(describing: error))") completion(nil) return } completion(localURL) } task.resume() } }```
0
0
78
4d