Discuss Swift.

Swift Documentation

Post

Replies

Boosts

Views

Activity

How to prevent initial rotation of a node when following a UIBezierPath?
Problem = I have a locomotive trying to follow an oval-shaped UIBezierPath. The challenge is that when I use orientToPath:true in my call to SKAction.follow, the locomotive immediately rotates even though the locomotive is initially positioned on the straight portion of the oval before it reaches the rounded portion of the oval. If I could prevent this initial rotation, then the rotation would not happen until it reached the rounded portion of the oval - as it should. So, can you please provide some guidance as to how I could prevent this initial rotation? Here is the code: func createTrainPath() { // this custom method ensures that the locomotive // moves CW, versus CCW trackPath = getBezierPath(theNode: myTrain, offset: 0.0) } // createTrainPath func startFollowTrainPath() { let theSpeed = Double(5*thisSpeed) var trainAction = SKAction.follow( trackPath.cgPath, asOffset: true, orientToPath: true, // <== speed: theSpeed) trainAction = SKAction.repeatForever(trainAction) myTrain.run(trainAction, withKey: runTrainKey) } // startFollowTrainPath
3
0
601
Jan ’24
SwiftData Crashes When Using Custom Migration.
I have 2 vesrion schema and Migration plan. Version 2: Add new properties and Property renamed. static let release: ModelContainer = { do { let schema = Schema(versionedSchema: V2Schema.self) let appGroupURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "***") let databaseURL = appGroupURL?.appending(path: "Models.sqlite") let databaseName = "Models" let configuration = ModelConfiguration(databaseName, schema: schema, url: databaseURL!, cloudKitDatabase: .automatic) return try ModelContainer(for: schema, migrationPlan: ModelMigrationPlan.self, configurations: [configuration]) } catch { fatalError(error.localizedDescription) } }() enum ModelMigrationPlan: SchemaMigrationPlan { static var schemas: [VersionedSchema.Type] { [V1Schema.self, V2Schema.self] } static var stages: [MigrationStage] { [v1ToV2MigrationStage] } } When I test migration in UnitTest, It works fine. But In running in device, error is occurred. error: Store failed to load. <NSPersistentStoreDescription: 0x1077aa330> (type: SQLite, url: file:///private/var/mobile/Containers/Shared/AppGroup/***/Model.sqlite) with error = Error Domain=NSCocoaErrorDomain Code=134504 "Cannot use staged migration with an unknown model version." UserInfo={NSLocalizedDescription=Cannot use staged migration with an unknown model version.} with userInfo { NSLocalizedDescription = "Cannot use staged migration with an unknown model version."; } Has anyone experienced this same problem or know a solution?
4
0
857
Jan ’24
Strange visionOS Simulator
I found that my visionOS Simulator is very strange. Many functions and features are missing. For example, I learned from the Internet that the immersive scenes of Environments in their visionOS Simulator can be opened, but I click There was no response after the attack. There are not only these, but also many system features. I saw on the Internet that other developers have them, and I am missing. I'm worried that this will have an impact on me when testing my app. May I ask why? Some information: My updated Xcode version is the latest Xcode15.1Beta. Device: iMac (2021) Simulator system number: 21N305
1
0
555
Jan ’24
NWConnection, how to catch error?
I have a NWConnection, that if an invalid (ip/port), is entered, I get in debug the error: nw_socket_handle_socket_event [C1.1.1:1] Socket SO_ERROR 61. But I can't seem to trap that error. I have as my stateChangeHandler: I am creating my connection: let tcpOptions = NWProtocolTCP.Options() tcpOptions.enableKeepalive = true tcpOptions.keepaliveIdle = 2 tcpOptions.keepaliveCount = 2 tcpOptions.keepaliveInterval = 2 let params = NWParameters(tls: nil, tcp: tcpOptions) nwConnection:NWConnection(host: NWEndpoint.Host(host), port: NWEndpoint.Port(port)!, using: params). (with known nonexistent ip/port). I was hopping when I did a .start(), I would get an error in my state handler: // =============================================================================== func stateDidChange(to state: NWConnection.State) { Swift.print("State change") switch state { case .waiting(let error): print("Client waiting") connectionDidFail(error: error) case .ready: print("Client connection ready") case .failed(let error): print("Client failed") connectionDidFail(error: error) case .preparing: print("client preparing") case .setup: print("client setup") case .cancelled: print("client cancelled") default: print("Client unknown") break } } But it doesn't trap an error. So, where is this error coming from (I know the cause), but I want to trap it (in case a user puts in a wrong ip/port)
4
0
1k
Jan ’24
Unable to consistently detect lock/unlock events with Swift
I need to detect lock & unlock events in my swift iOS application. I have tried using AppDelegate functions like UIApplicationProtectedDataWillBecomeUnavailable & UIApplicationProtectedDataDidBecomeAvailable to record the lock and unlock events respectively, but have found this to be inconsistent. UIApplicationProtectedDataWillBecomeUnavailable is not called immediately after the lock event, and sometimes misses the event altogether. Is there a different approach to this problem that guarantees detecting lock & unlock correctly every time?
2
0
763
Jan ’24
OpenAPI Swift Generator
Hello, I'm using the generator to create a client from this API: https://github.com/griptape-ai/griptape-cloud-control-plane/blob/main/models/Griptape.openapi.json Everything seems fine until I go to call a method. I get an error on a DateTime format mismatch in the response. Client error - cause description: 'Unknown', underlying error: DecodingError: dataCorrupted - at : Expected date string to be ISO8601-formatted. (underlying error: <nil>), Is there a decoder option or something I can attach to the generated client code to adjust for this?
2
0
684
Jan ’24
How do you make lines of code only for a specific destination in Xcode?
Hi! I am trying to create an iOS application but also for visionOS. In the target settings, I have iPhone and Vision Pro added under the supported destinations. The problem that I am running into is that the Firebase messaging and the user notifications are not supported with Vision Pro. Is there anyway to just make those lines of code only for the iOS supported destination? If you could help, that would be greatly appreciated!
1
0
435
Jan ’24
Swift Playground Bundle can't find Compiled CoreML Model (.mlmodelc)
I have been attempting to debug this for over 10 hours... I am working on implementing Apple's MobileNetV2 CoreML model into a Swift Playgrounds. I performed the following steps Compiled CoreML model in regular Xcode project Moved Compiled CoreML (MobileNetV2.mlmodelc) model to Resources folder of Swift Playground Copy Paste the model class (MobileNetV2.swift) into the Sources folder of Swift Playground Use UIImage extensions to resize and convert UIImage into CVbuffer Implement basic code to run the model. However, every time I run this, it keeps giving me this error: MobileNetV2.swift:100: Fatal error: Unexpectedly found nil while unwrapping an Optional value From the automatically generated model class function: /// URL of model assuming it was installed in the same bundle as this class class var urlOfModelInThisBundle : URL { let bundle = Bundle(for: self) return bundle.url(forResource: "MobileNetV2", withExtension:"mlmodelc")! } The model builds perfectly, this is my contentView Code: import SwiftUI struct ContentView: View { func test() -> String{ // 1. Load the image from the 'Resources' folder. let newImage = UIImage(named: "img") // 2. Resize the image to the required input dimension of the Core ML model // Method from UIImage+Extension.swift let newSize = CGSize(width: 224, height: 224) guard let resizedImage = newImage?.resizeImageTo(size: newSize) else { fatalError("⚠️ The image could not be found or resized.") } // 3. Convert the resized image to CVPixelBuffer as it is the required input // type of the Core ML model. Method from UIImage+Extension.swift guard let convertedImage = resizedImage.convertToBuffer() else { fatalError("⚠️ The image could not be converted to CVPixelBugger") } // 1. Create the ML model instance from the model class in the 'Sources' folder let mlModel = MobileNetV2() // 2. Get the prediction output guard let prediction = try? mlModel.prediction(image: convertedImage) else { fatalError("⚠️ The model could not return a prediction") } // 3. Checking the results of the prediction let mostLikelyImageCategory = prediction.classLabel let probabilityOfEachCategory = prediction.classLabelProbs var highestProbability: Double { let probabilty = probabilityOfEachCategory[mostLikelyImageCategory] ?? 0.0 let roundedProbability = (probabilty * 100).rounded(.toNearestOrEven) return roundedProbability } return("\(mostLikelyImageCategory): \(highestProbability)%") } var body: some View { VStack { let _ = print(test()) Image(systemName: "globe") .imageScale(.large) .foregroundColor(.accentColor) Text("Hello, world!") Image(uiImage: UIImage(named: "img")!) } } } Upon printing my bundle contents, I get these: ["_CodeSignature", "metadata.json", "__PlaceholderAppIcon76x76@2x~ipad.png", "Info.plist", "__PlaceholderAppIcon60x60@2x.png", "coremldata.bin", "{App Name}", "PkgInfo", "Assets.car", "embedded.mobileprovision"] Anything would help 🙏 For additional reference, here are my UIImage extensions in ExtImage.swift: //Huge thanks to @mprecke on github for these UIImage extension function. import Foundation import UIKit extension UIImage { func resizeImageTo(size: CGSize) -> UIImage? { UIGraphicsBeginImageContextWithOptions(size, false, 0.0) self.draw(in: CGRect(origin: CGPoint.zero, size: size)) let resizedImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return resizedImage } func convertToBuffer() -> CVPixelBuffer? { let attributes = [ kCVPixelBufferCGImageCompatibilityKey: kCFBooleanTrue, kCVPixelBufferCGBitmapContextCompatibilityKey: kCFBooleanTrue ] as CFDictionary var pixelBuffer: CVPixelBuffer? let status = CVPixelBufferCreate( kCFAllocatorDefault, Int(self.size.width), Int(self.size.height), kCVPixelFormatType_32ARGB, attributes, &pixelBuffer) guard (status == kCVReturnSuccess) else { return nil } CVPixelBufferLockBaseAddress(pixelBuffer!, CVPixelBufferLockFlags(rawValue: 0)) let pixelData = CVPixelBufferGetBaseAddress(pixelBuffer!) let rgbColorSpace = CGColorSpaceCreateDeviceRGB() let context = CGContext( data: pixelData, width: Int(self.size.width), height: Int(self.size.height), bitsPerComponent: 8, bytesPerRow: CVPixelBufferGetBytesPerRow(pixelBuffer!), space: rgbColorSpace, bitmapInfo: CGImageAlphaInfo.noneSkipFirst.rawValue) context?.translateBy(x: 0, y: self.size.height) context?.scaleBy(x: 1.0, y: -1.0) UIGraphicsPushContext(context!) self.draw(in: CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)) UIGraphicsPopContext() CVPixelBufferUnlockBaseAddress(pixelBuffer!, CVPixelBufferLockFlags(rawValue: 0)) return pixelBuffer } }
5
1
2.1k
Jan ’24
Xcode 14.3.1 Type Y has no member x
Hi, We are using Github actions to build our CI/CD. In github actions the highest xcode version possible to use 14.3.1. When trying to build the app using fastlane we encounter several errors Type 'Circle' has no member 'circle' Type 'Shape' has no member 'capsule' When looking at the documentation for circle and capsule both are @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) capsule @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) extension Shape where Self == Capsule { /// A capsule shape aligned inside the frame of the view containing it. /// /// A capsule shape is equivalent to a rounded rectangle where the corner /// radius is chosen as half the length of the rectangle's smallest edge. public static var capsule: Capsule { get } /// A capsule shape aligned inside the frame of the view containing it. /// /// A capsule shape is equivalent to a rounded rectangle where the corner /// radius is chosen as half the length of the rectangle's smallest edge. public static func capsule(style: RoundedCornerStyle) -> Self } circle @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) extension Shape where Self == Circle { /// A circle centered on the frame of the view containing it. /// /// The circle's radius equals half the length of the frame rectangle's /// smallest edge. public static var circle: Circle { get } } Does anyone have any idea why would an xcode 14.3.1 and iOS 13.0 available syntax is causing this error? Thanks
0
1
321
Jan ’24
Flutter MSAL SSO with webview
Hi, I am using flutter MSAL SSO with flutter_inappwebview and azure_flutter_authentication package to login to the app. let viewController: UIViewController = UIViewController.keyViewController! let webviewParameters = MSALWebviewParameters(authPresentationViewController: viewController) webviewParameters.webviewType = .default I am trying to open another application in webview by using flutter_inappwebview, so that there will be a silent log in using MSAL SSO option in iOS device. But its not working InAppWebView( key: webViewKey, initialUrlRequest: URLRequest(url: Uri.parse(widget.url)), initialOptions: options, pullToRefreshController: pullToRefreshController, onWebViewCreated: (controller) { webViewController = controller; }, onLoadStart: (controller, url) { logger.d("printing webview controller type: " + controller.runtimeType.toString()); setState(() { this.url = url.toString(); urlController.text = this.url; isLoading = false; }); }, androidOnPermissionRequest: (controller, origin, resources) async { return PermissionRequestResponse( resources: resources, action: PermissionRequestResponseAction.GRANT); }, shouldOverrideUrlLoading: (controller, navigationAction) async { var uri = navigationAction.request.url!; if (![ "http", "https", "file", "chrome", "data", "javascript", "about" ].contains(uri.scheme)) { if (await canLaunch(url)) { // Launch the App await launch( url, ); // and cancel the request return NavigationActionPolicy.CANCEL; } } return NavigationActionPolicy.ALLOW; }, onLoadStop: (controller, url) async { pullToRefreshController?.endRefreshing(); setState(() { this.url = url.toString(); urlController.text = this.url; }); }, onLoadError: (controller, url, code, message) { pullToRefreshController?.endRefreshing(); }, onProgressChanged: (controller, progress) { if (progress == 100) { pullToRefreshController?.endRefreshing(); } setState(() { this.progress = progress / 100; urlController.text = this.url; }); }, onUpdateVisitedHistory: (controller, url, androidIsReload) { setState(() { this.url = url.toString(); urlController.text = this.url; }); }, onConsoleMessage: (controller, consoleMessage) { print(consoleMessage); }, ), How to should I pass the login session from swift code to inappwebview in flutter? Please help me with this. I really appreciate it. Its working fine with android devices. The problem is from iOS devices.
0
0
821
Jan ’24
Crash on launch, while in review - but no crash in Xcode or TestFlight
Hi all! My new iOS app (first one in Swift and SpriteKit, was using ObjectiveC and Cocos2D before, a few years back) - got rejected with the dreaded "We were unable to review your app as it crashed on launch.", That's especially bad news when it never ever crashed on any on our devices when testing (variety of phones, iPads and all sort of iOS) either in debug or release, before submission. So no luck repro-ing! The crashlog text file apple review team sent back, renamed as .crash, seems to open in Xcode (right click on it) when linked to the right project and seems to point in the leaderboard code fetching the local authenticated user's score. This is some code that I shamelessly copy/pasted from a StackOverflow page a few months ago, and seemed to work right away so moved-on back then, but something must be unsafe in there (sorry, bit of a rookie with Swift optionals etc). Any help would be much appreciated as this code seems to work fine in debug, without warnings or anything, and also works fine in release using TestFlight - so we simply cannot repro the apple QA issue, and we need to fix it blind! This is the function below that is crashing, right on the line that has the "{ player, _, _ in ": func sync_hiscore() { if (GKLocalPlayer.local.isAuthenticated) { if #available(iOS 14.0, *) { GKLeaderboard.loadLeaderboards( IDs: ["HatStacker_LD01"] ) { leaderboards, _ in leaderboards?[0].loadEntries( for: [GKLocalPlayer.local], timeScope: .allTime ) { player, _, _ in // &lt;&lt;&lt;&lt; !!! CRASHES HERE!! if ( player!.score &gt; player_hiscore) { player_hiscore = player!.score } } } } } } I've also attached the full crashlog if that's of any help! Many thanks all, sorry for such a Swift rookie question, but to add to the confusion this is also the first time one of our apps gets rejected for such an obvious bad crash at launch, that no one has seen during our weeks of testing! Any idea why it's only in release and only in the apple HQ/review env that we get that error? Could they have an invalid Game Center account that is confusing the "player" score fetching? Cheers, JBB HatStacker_build4.crash
5
0
2.3k
Jan ’24
Reading multi parts of a file concurrently
I have a need to read first half and second half of a file concurrently. Is there any best practices for this scenario? BTW, I did research on DispatchIO but it turned out DispatchIO is all about asynchronous operations on a single file handle; it cannot perform parallel reading. // naive approach Task { fileHandle.read(into:buffer) } Task { // seek to file size / 2 fileHandle.read(into:buffer) }
5
0
743
Jan ’24
Swift and C++ In The Same Project
Hi -- I am attempting to use C++ and Swift in a single project but I am struggling with finding the proper way to do this. Ideally I want to have both my C++ and Swift code in the same project and not use a framework to keep them separate. As an example, how would I create an object of the following C++ class: class Foo { public: Foo() { // do stuff } } From what I read, it should be as simple as this: let foo = Foo() But Xcode says it Cannot find 'Foo' in scope. How do I import Foo into my Swift code? Is there a project setting that needs to be changed to automatically make my C++ classes available? Or do I need to create a Clang module (as described in this page: https://www.swift.org/documentation/cxx-interop/#importing-c-into-swift) to expose the C++ code to Swift? If so, where in my Xcode project should that go? I am using Xcode 15.2 on macOS 14.2.1. I have also set the C++ and Objective-C Interoperability setting for my project to C++/Objective-C++.
3
0
3k
Jan ’24
Custom library/framework with ARCHS = $(ARCHS_STANDARD) not running in iOS simulator
We have one custom library/framework with ARCHS = $(ARCHS_STANDARD) under build settings. I export the library/framework with "Any iOS device" target and export the library/framework. But when we try to integrate this custom library/framework in to another project ( M1 with xcode 14.2 with rosetta enabled ) its not running in iOS simulator. Getting error like. : Unsupported Swift architecture Note : Its running fine in real device.
2
0
632
Jan ’24
Crash iOS 17.1.2: SIGSEGV _swift_release_dealloc (libswiftCore.dylib)
Hello! I'm developing a SDK and a customer is experiencing a very rare crash (happening for < 10 users) for which there are no clear repro steps. In the attached backtrace of the crash, there are two threads #13 and #17 which seem to be accessing the same part of the code (named MyMethod2 in the file). Thread #17 is the one crashing during deallocation of some protobuf objects. We designed MyMethod2 to be called by at most one thread at any point in time by using a serial DispatchQueue. My question is: can we tell for sure that the threads #13 and #17 shown in the file were executing that shared code simultaneously just by looking at the trace? If so, there'd be a concurrency bug in my code that I need to fix, but I haven't found anything suspicious. If on the other hand, these two threads were both used by the serial queue but at different times, then the problem is elsewhere. Thank you for your help! The two threads: Thread 13 name: Thread 13: 0 libsystem_kernel.dylib 0x00000001f61a0cb0 write (libsystem_kernel.dylib) 1 CoreFoundation 0x00000001aed14f68 fileWrite (CoreFoundation) 2 CoreFoundation 0x00000001aed14c40 CFWriteStreamWrite (CoreFoundation) 3 [MyHiddenAppName] 0x0000000107b81f8c NSOutputStream.write(_:) 4 [MyHiddenAppName] 0x0000000107ab6640 specialized MyMethod2 5 [MyHiddenAppName] 0x0000000107ab6cf0 partial apply for closure #1 in MyMethod1 6 [MyHiddenAppName] 0x0000000102ba0538 thunk for @escaping @callee_guaranteed () -> () (<compiler-generated>:0) 7 libdispatch.dylib 0x00000001b6c4f6a8 _dispatch_call_block_and_release (libdispatch.dylib) [...] Thread 17 name: Thread 17 Crashed: 0 libswiftCore.dylib 0x00000001a8467d70 _swift_release_dealloc (libswiftCore.dylib) 1 libswiftCore.dylib 0x00000001a8469424 bool swift::RefCounts<swift::RefCountBitsT<(swift::RefCountInlinedness)1>>::doDecrementSlow<(swift::PerformDeinit)1>(swift::RefCountBitsT<(swift::RefCountInlinedness)1>, unsigned int) (libswiftCore.dylib) 2 [MyHiddenAppName] 0x0000000107a45b54 destroy for MyProtoStruct4 3 [MyHiddenAppName] 0x0000000107a55c64 outlined destroy of (MyProtoStruct2.OneOfEnum, MyProtoStruct2.OneOfEnum) 4 [MyHiddenAppName] 0x0000000107a4503c MyProtoStruct4._StorageClass.__deallocating_deinit 5 libswiftCore.dylib 0x00000001a8467d88 _swift_release_dealloc (libswiftCore.dylib) 6 libswiftCore.dylib 0x00000001a8469424 bool swift::RefCounts<swift::RefCountBitsT<(swift::RefCountInlinedness)1>>::doDecrementSlow<(swift::PerformDeinit)1>(swift::RefCountBitsT<(swift::RefCountInlinedness)1>, unsigned int) (libswiftCore.dylib) 7 [MyHiddenAppName] 0x0000000107a6a91c destroy for MyProtoStruct3 [...] 80 [MyHiddenAppName] 0x0000000107ab6108 specialized MyMethod2 81 [MyHiddenAppName] 0x0000000107ab6cf0 partial apply for closure #1 in MyMethod1 82 [MyHiddenAppName] 0x0000000102ba0538 thunk for @escaping @callee_guaranteed () -> () (<compiler-generated>:0) 83 libdispatch.dylib 0x00000001b6c4f6a8 _dispatch_call_block_and_release (libdispatch.dylib) [...] crash_backtrace.txt
3
0
1.5k
Jan ’24
Trying to extract Song Array from Shazamkit
I am try to extract the audio file url from Shazamkit, it is deep inside the hierarchy of SHMediaItem > songs > previewAssets > url when I access the url with like this: let url = firstItem.songs[0].previewAssets?[0].url I am getting a warning like this: here is the Variable Viewer this is what I have done so far: struct MediaItems: Codable { let title: String? let subtitle: String? let shazamId: String? let appleMusicId: String? let appleMusicUrL: URL? let artworkUrl: URL? let artist: String? let matchOffset: TimeInterval? let videoUrl: URL? let webUrl: URL? let genres: [String] let isrc: String? let songs: [Song]? } extension SwiftFlutterShazamKitPlugin: SHSessionDelegate{ public func session(_ session: SHSession, didFind match: SHMatch) { let mediaItems = match.mediaItems if let firstItem = mediaItems.first { // extracting the url let url = firstItem.songs[0].previewAssets?[0].url let _shazamMedia = MediaItems( title:firstItem.title!, subtitle:firstItem.subtitle!, shazamId:firstItem.shazamID!, appleMusicId:firstItem.appleMusicID!, appleMusicUrL:firstItem.appleMusicURL!, artworkUrl:firstItem.artworkURL!, artist:firstItem.artist!, matchOffset:firstItem.matchOffset, videoUrl:firstItem.videoURL!, webUrl:firstItem.webURL!, genres:firstItem.genres, isrc:firstItem.isrc!, songs:firstItem.songs ) do { let jsonData = try JSONEncoder().encode([_shazamMedia]) let jsonString = String(data: jsonData, encoding: .utf8)! self.callbackChannel?.invokeMethod("matchFound", arguments: jsonString) } catch { callbackChannel?.invokeMethod("didHasError", arguments: "Error when trying to format data, please try again") } } }
3
0
759
Jan ’24