Discuss Swift.

Swift Documentation

Post

Replies

Boosts

Views

Activity

Access all files in UIDocumentPickerController while picking folder
Hello, I need to get all files (recursively) from an iCloud Drive folder. So I use UIDocumentPickerController with UTType.folder. Then I use FileManager to get all files from the picked folder, but when I try to access it with startAccessingSecurityScopedResource it return false. It's work perfectly if I dont get files by FileManager but directly by the UIDocumentPickerController when configured for multiple files selection. How can I access to all files from a picked directory with permission granted ? Is it at least possible ? Thanks
3
0
726
Jul ’23
Question about Property Observer
I'm studying swift to develop macOS app so far. I wrote a following code to learn property observer. var x:Int var y:Int var oppositePos:coordinatePoint{ get{ coordinatePoint(x: -x, y: -y) } set{ x = -newValue.x y = -newValue.y } } } I want to implement property observer on opposites property so I changed code as follows : var x:Int var y:Int var oppositePos:coordinatePoint { willSet{ print("\(oppositePos) is changed to \(newValue)") } didSet{ print("\(oldValue) is changed to \(oppositePos)") } } } after changing code, I ran it but I got following error messages: Value type 'coordinatePoint' cannot have a stored property that recursively contains it Missing argument for parameter 'oppositePos' in call My question: property observer is available on this property? if so, what should I change in this code? if someone give me an advice to fix errors, I'd be very appreciate. thanks, c00012
3
0
275
Jul ’23
How to declare Privacy manifest
It is stated that From Fall 2023 you’ll receive an email from Apple if you upload an app to App Store Connect that uses required reason API without describing the reason in its privacy manifest file. From Spring 2024, apps that don’t describe their use of required reason API in their privacy manifest file won’t be accepted by App Store Connect. There are some answers here : https://developer.apple.com/videos/play/wwdc2023/10060/ but far from answering all questions. I have questions on how to implement: Where exactly is the privacy manifest ? How to create it, from which file template in Xcode ? WWDC speaks of a PrivacyInfo.xcprivacy (does it require a more recent version of Xcode than 14.2). WWDC describes a framework case. Is it the same for a "final" app ? is there a specific format for describing the reason ? Or just plain text. Is this text visible to the user or only to reviewer ? does it apply retroactively to apps already in AppStore (do they need to be resubmitted ?). It seems not. So I tried, in an iOS App, to declare the PrivacyInfo.xcprivacy as explained, with Xcode 14.2, using plist template, to no avail. Really not clear on how to proceed or even start… We would need a clear step by step tutorial with all prerequisites (Xcode or MacOS versions needed for instance).
14
1
14k
Jul ’23
SQLite - Select statement to extract 1 year of data
I have an SQLite table that holds a fund name, as a string, a time stamp, as an iso8601 string, and a close, as a double. SQLite appears to call strings text and a double a real. In the function below, I query this table with a select statement to return the last year of data based on the latest date in the table. To get the latest date I have a separate function that finds the latest date, converts if from a string to a date, subtracts 1 year from the date then converts it back to an iso8601 date string. It is this date string that is being passed into the function below as the variable startingDate. The function below works just fine and is relatively fast. What I am trying to determine is there a way to modify the select statement in the function below such that it does everything and I will no longer have to separately calculate the starting date and pass it in? func QuerySQLiteData(db: OpaquePointer?, fundName: String, startingDate: String) -> [TradingDay] { var queryResults: [TradingDay] = [] let timeStampFormatter = ISO8601DateFormatter() let queryTradingDaysStatement = """ Select FundName, TimeStamp, Close FROM TradingDays WHERE FundName = '\(fundName)' AND TimeStamp >= '\(startingDate)' ORDER By TimeStamp ASC ; """ var queryTradingDaysCPtr: OpaquePointer? var tradingDay: TradingDay = TradingDay(fundName: "", timeStamp: Date(), close: 0.0) if sqlite3_prepare_v2(db, queryTradingDaysStatement, -1, &queryTradingDaysCPtr, nil) == SQLITE_OK { while (sqlite3_step(queryTradingDaysCPtr) == SQLITE_ROW) { let fundName = sqlite3_column_text(queryTradingDaysCPtr, 0) let timeStamp = sqlite3_column_text(queryTradingDaysCPtr, 1) let close = sqlite3_column_double(queryTradingDaysCPtr, 2) let fundNameAsString = String(cString: fundName!) let timeStampAsString = String(cString: timeStamp!) let timeStampAsDate = timeStampFormatter.date(from: timeStampAsString)! tradingDay.fundName = fundNameAsString tradingDay.timeStamp = timeStampAsDate tradingDay.close = close queryResults.append(tradingDay) } // end while loop } else { let errorMessage = String(cString: sqlite3_errmsg(db)) print("\nQuery is not prepared \(errorMessage)") } sqlite3_finalize(queryTradingDaysCPtr) return queryResults }
5
0
533
Jul ’23
In app purchase goes to Entered Billing Retry after free trail
I have a VPN application published in the app store. Used Ikev2 for this personal VPN. There are two in-app purchases. One is 'Monthly' and another is 'Yearly' with 3 days free trial. We have seen something strange for the yearly subscriptions which has free trail, the cancellation reason through the billing issue is too high like 70-80% due to billing retry state. Some other apps which have billing issues under 10% always. We have done some research and found that if the user doesn't cancel and Apple is unable to charge then it goes to a billing retry state. If users don't like the app, they could cancel their subscription/free trail easily but they are not doing this and why Apple unable to charge the bill after the trial ends. Am i missing something in the developer end?
2
0
609
Jul ’23
Unarchiving - can't get new method to work
I've previously used NSKeyedUnarchiver.unarchiveTopLevelObjectWithData to unarchive data that I've previously archived and stored in a data model. I'm now trying to switch from NSKeyedUnarchiver.unarchiveTopLevelObjectWithData to unarchivedObject(ofClass:from:) as NSKeyedUnarchiver.unarchiveTopLevelObjectWithData is deprecated. I've tried an absolute pile of attempts to get this to work and I feel I've just gotten further and further away from working code. Below is my original code to archive and unarchive. Could someone please show me what needs to be done for the conversion to the new method? Thanks. ARCHIVING CODE var selectedAmenities = [String: String]() var archivedAmenities: Data! do { archivedAmenities = try NSKeyedArchiver.archivedData(withRootObject: selectedAmenities, requiringSecureCoding: false) } catch { print("Couldn't archive the Amenities.") } UNARCHIVING CODE var selectedAmenities = [String: String]() do { let unArchivedAmenities = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(campSight.amenities!) selectedAmenities = unArchivedAmenities as! [String: String] } catch { print("Couldn't unarchive the Amenities.") }
0
0
252
Jul ’23
swift: create URLCredential() with newly generated certificate/private key
Hello! I am a newby into Apple ecosystem/swift development so forgive me if it is a trivial question. But I cannot find a good tutorial/article on this topic. I am trying to implement a mutual TLS for my iOS application. To generate key/certificate I use https://github.com/apple/swift-* libraries. Next moving to mTLS logic. I use URLSessionDelegate for this purpose as it seems it is the only way to implement mTLS. The NSURLAuthenticationMethodServerTrust part seems fine. Now I am trying to implement the client side of the authentication. let identity = ??? let urlCredential = URLCredential( identity: identity, certificates: nil, persistence: .none) completionHandler(.useCredential, urlCredential) And here is my question. What is the correct/idiomatic way to create SecIdentityRef object out of a private key/certificate? Certificate can be serialized into DER form if needed. I googled for a whole day and did not find a clear information on how to create the identity I need. If anyone has some information on this topic, could you please help me?
1
0
597
Jul ’23
Project scorpion
Je poste mon message en français parce que je cherche 2 ou 3 personne sur Marseille avec un bon niveau en Swift et en animation 3d mon numéro si vous voulez m’envoyer un message pour en savoir plus 06.34.01.81.05
0
0
170
Jul ’23
Is there no V2Ray library on IOS?
I am programming ios app with swift language about vpn. v2ray protocols must be used in this application. None of the libraries listed on github are working or have been removed. For example, none of the following libraries work: v2ray_mobile_lib SwiftV2Ray-1 sing-box SwiftV2Ray Do you know a library or method for programming v2ray in the ios operating system in swift language that you can introduce?
6
1
1.2k
Jul ’23
determine the current person’s head pose precisely in ARKit’s face recognition
Hi there, I'd like to accurately determine the current person's head pose in ARKit's face recognition. Here is my code, but it was not precise. fileprivate func getCurrentDirection(faceAnchor: ARFaceAnchor) -> CommandDirection?{ let transform = faceAnchor.transform let pitch = atan2(-transform.columns.2.y, transform.columns.2.z) let yaw = atan2(transform.columns.2.x, transform.columns.2.z) var direction: CommandDirection? var horizontalTurn = false if yaw > 0.5 { horizontalTurn = true direction = .right } else if yaw < -0.3 { horizontalTurn = true direction = .left } if(!horizontalTurn){ if pitch > 0.5 { direction = .down } else if pitch < -0.1 { direction = .up } } return direction } func renderer(_ renderer: SCNSceneRenderer, didUpdate node: SCNNode, for anchor: ARAnchor) { guard let faceAnchor = anchor as? ARFaceAnchor, let currentRotationDirection = getCurrentDirection(faceAnchor: faceAnchor) else { return } }
0
0
279
Jul ’23
Save texture as Tiff
I'm trying to save metal textures in a lossless compressed format. I've tried png and tiff, but I run into the same problem: the pixel data changes after save and load when we have transparency. Here is the code I use to save a Tiff: import ImageIO import UIKit import Metal import MobileCoreServices extension MTLTexture { func saveAsLosslessTIFF(url: URL) throws { guard let context = CIContext() else { return } guard let colorSpace = CGColorSpace(name: CGColorSpace.linearSRGB) else { return } guard let ciImage = CIImage(mtlTexture: self, options: [.colorSpace : colorSpace]) else { return } guard let cgImage = context.createCGImage(ciImage, from: ciImage.extent) else { return } // create a dictionary with TIFF compression options let tiffCompression_LZW = 5 let options: [String: Any] = [ kCGImagePropertyTIFFCompression as String: tiffCompression_LZW, kCGImagePropertyDepth as String: depth, kCGImagePropertyPixelWidth as String: width, kCGImagePropertyPixelHeight as String: height, ] let fileDestination = CGImageDestinationCreateWithURL(url as CFURL, kUTTypeTIFF, 1, nil) guard let destination = fileDestination else { throw RuntimeError("Unable to create image destination.") } CGImageDestinationAddImage(destination, cgImage, options as CFDictionary) if !CGImageDestinationFinalize(destination) { throw RuntimeError("Unable to save image to destination.") } } } I can then load the texture like this: func loadTexture(url:URL) throws -> MTLTexture { let usage = MTLTextureUsage(rawValue: MTLTextureUsage.renderTarget.rawValue | MTLTextureUsage.shaderRead.rawValue | MTLTextureUsage.shaderWrite.rawValue) return try loader.newTexture(URL:url,options:[MTKTextureLoader.Option.textureUsage:usage.rawValue,MTKTextureLoader.Option.origin:MTKTextureLoader.Origin.flippedVertically.rawValue]) } After saving and then loading the texture again, I want to get back the exact same texture. And I do, if there is no transparency. Transparent pixels, however, are transformed in a way that I don't understand. Here is an example pixel: [120, 145, 195, 170] -> [144, 174, 234, 170] My first guess would be that something is trying to undo a pre-multiplied alpha that never happened. But the numbers don't seem to work out. For example, if that were the case I'd expect 120 to go to (120 * 255) / 170 = 180 , not 144. Any idea what I am doing wrong?
9
0
1.1k
Jul ’23
CoreML Error: "Failed to unarchive update parameters. Model should be re-compiled"
I am building an image recognition app for iPhone, using Swift, Vision, CoreML and the pretrained Resnet50 model. When I run MLUpdateTask, it gives me an error that my model (Resnet50) needs to be re-compiled. I am using Xcode 14.3.1 on Ventura 13.4.1 (c). Here's the error message: EXCEPTION from MLUpdateTask: Error Domain=com.apple.CoreML Code=6 "Failed to unarchive update parameters. Model should be re-compiled." UserInfo={NSLocalizedDescription=Failed to unarchive update parameters. Model should be re-compiled.} Here's the code snippet: struct ImageCoreML { let sourceModelURL = Bundle.main.url(forResource: "Resnet50", withExtension: ".mlmodelc")! static let docsURL: URL = { return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] }() let updatedModelURL = docsURL.appendingPathComponent("ImageID") .appendingPathExtension("mlmodelc") init() { if !FileManager.default.fileExists(atPath: updatedModelURL.path) { do { try FileManager.default.copyItem(at: sourceModelURL, to: updatedModelURL) return } catch { print("copy models Error: \(error)") } } } private func completionHandler(_ context: MLUpdateContext) { let updatedModel = context.model let fileManager = FileManager.default do { try updatedModel.write(to: self.updatedModelURL) print("Updated model saved to:\n\t\(self.updatedModelURL)") } catch let error { print("Could not save updated model to the file system: \(error)") return } } // Update the CNN model with the saved image. func updateModel(croppedImage: CVPixelBuffer?, personLabel: String) { print("updateModel()") guard let pixelBuffer = croppedImage else { print("ERROR: cannot convert cropped image to cgImage buffer") return } var featureProviders = [MLFeatureProvider]() let imageFeature = MLFeatureValue(pixelBuffer: pixelBuffer) let personLabel = MLFeatureValue(string: personLabel) let dataPointFeatures: [String: MLFeatureValue] = ["image": imageFeature, "personID": personLabel] if let provider = try? MLDictionaryFeatureProvider(dictionary: dataPointFeatures) { featureProviders.append(provider) } let trainingData = MLArrayBatchProvider(array: featureProviders) do { let updateTask = try MLUpdateTask(forModelAt: self.updatedModelURL, trainingData: trainingData, configuration: nil, completionHandler: completionHandler) updateTask.resume() } catch { print("EXCEPTION from MLUpdateTask:\n\(error)") return } } }
1
0
336
Jul ’23
support and guidence
Subject: In Search of Swift Mentorship Hello Community, I'm Abdallah, a self-taught iOS developer with a solid understanding of the basics. However, I'm at a point in my learning where I need some real-world experience to truly refine my skills. I'm seeking an experienced Swift developer for personalized mentorship and guidance. I'm ready to invest my time, and I'm open to compensating for yours. I believe this will be a significant step for my growth as an IOS developer. If you're interested or can recommend someone, please let me know. I'm excited about this next phase of my journey and eager to contribute to actual projects. Best, Abdallah
1
0
458
Jul ’23
Xcode 15 beta: unable to load standard library for target 'arm64-apple-ios17.0-simulator'
In Xcode 14, Swift Package libraries can be built with the following command: swift build -v -Xswiftc "-sdk" -Xswiftc "`xcrun --sdk iphonesimulator --show-sdk-path`" -Xswiftc "-target" -Xswiftc "x86_64-apple-ios12.3-simulator" But in Xcode 15 beta 5, I'm encountering an error: <unknown>:0: error: unable to load standard library for target 'x86_64-apple-ios12.3-simulator' The error persists even when I change the OS version (such as to ios17.0) or change the architecture to arm64. Has there been a change to the behavior of the swift command in Xcode 15 that I should be aware of?
2
0
1.1k
Aug ’23
Swift 5.9 is compatible with which minimum iOS version?
As the title suggests, I'm planning to use a combination of Swift and C++ in our application. Our app currently supports iOS 11 as the minimum version, but we're planning to update Xcode in the future and elevate our minimum version to iOS 12. With that in mind, can an app with iOS 12 as its minimum target use Swift 5.9? Additionally, is it possible for an app targeting at least iOS 12 to use a mix of Swift and C++?
1
0
2.0k
Aug ’23
[User Defaults] CFPrefsPlistSource Bug
Hi, I'm trying to save in the UserDefaults some identifiers for user-edited videos that we save on the Defaults. We save in this way: let data = try JSONEncoder().encode(myDesign) Defaults.setValue(data, forKey: myDesign.id) [...] allMyDesignsIds.append(myDesign.id) Defaults[.allUsersMyDesignsIds][userId] = allMyDesignsIds but we got an error when saving 10 elements, in the saving of the 8 element : 2023-08-01 17:44:08.656097+0200 AppName[12474:355884] [User Defaults] CFPrefsPlistSource<0x280d34480> (Domain: com.***.***.beta, User: kCFPreferencesCurrentUser, ByHost: No, Container: (null), Contents Need Refresh: Yes): Attempting to store >= 4194304 bytes of data in CFPreferences/NSUserDefaults on this platform is invalid. This is a bug in AppName or a library it uses. Description of keys being set: 985D7A7E-A0DC-4F26-BB1A-7202B106F49F: data value, size: 584750 Description of keys already present: 9E13F8B4-789F-4BA8-B788-6AAA924668D2: data value, size: 643913 63AC4E4F-7DA4-441D-9B77-5728689E6E74: data value, size: 642935 B0038C53-F4F6-46B7-996B-375F95E83FEA: data value, size: 637857 FDBC800B-89CE-4D2C-A89F-E96542A8EF93: data value, size: 611401 985D7A7E-A0DC-4F26-BB1A-7202B106F49F: data value, size: 584750 6D0524A1-E17D-4B96-B928-A9180D47107B: data value, size: 555791 DEBF1AF1-866A-42FD-8603-23DD1051E5FD: data value, size: 279035 87D83169-89B1-4A58-A63D-13CF118A5202: data value, size: 250166 35C48378-0CD3-457D-8BEB-DA41D855C3EE: data value, size: 226120 com.facebook.sdk:serverConfiguration631812514659191: data value, size: 3228 ... Total keys: 95 - Average approximate value size: 46758 bytes 2023-08-01 17:44:08.656513+0200 AppName[12474:355884] [User Defaults] CFPrefsPlistSource<0x280d34480> (Domain: com.***.***.beta, User: kCFPreferencesCurrentUser, ByHost: No, Container: (null), Contents Need Refresh: No): Transitioning into direct mode In this case the app cleans the values of Defaults[.allUsersMyDesignsIds][userId] leaving it empty... I tried it with the same videos always and also it only happens in the first launch and the first savings of videos in the Defaults... Anyone knows what can be happening? We discard the size of the values, because after this bug we continues saving videos without any problem. Thanks!!
2
0
426
Aug ’23
App trying to use compilation condition defined in SPM module
I'm defining a compilation condition in a SPM module that is being used by my iOS app. I'd like to be able to use the same compilation condition in my app code to determine behavior, but the condition doesn't seem to be getting set within my app. The condition is working as expected within the SPM module, just not in the iOS app that is importing the module. Package.swift excerpt target(..., swiftSettings: [.define("CONDITION", .when(configuration: .debug))] ) SPM Module #if CONDITION // Compiled and executes as expected #endif App #if CONDITION // Never compiled / triggered #endif
1
0
782
Aug ’23