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

How should I access @AppStorage and @SceneStorage values outside of views?
The two property wrappers @AppStorage and @SceneStorage are great because you can simply redeclare a property in multiple views to share the value and automatically update other views. But how should I access those same values outside of views? I have helper functions which are used in multiple views and which change behaviour based on those stored properties. I believe I could use the old NSUserDefaults.standard to reference the @AppStorage values, but is that the "right" way to do it, and how do I access @SceneStorage values?
8
2
8.3k
Nov ’23
Why does Combine assign crash when writing to an optional property?
This code crashes ("Unexpectedly found nil while unwrapping an Optional value") import Combine class Receiver { &#9;&#9;var value: Int! &#9;&#9;var cancellables = Set<AnyCancellable>([]) &#9;&#9;init(_ p: AnyPublisher<Int,Never>) { &#9;&#9;&#9;&#9;p.assign(to: \.value, on: self).store(in: &cancellables) &#9;&#9;} } let receiver = Receiver(Just(5).eraseToAnyPublisher()) It does not crash if I use p.sink { self.value = $0 }.store(in: &cancellables) instead of the assign, and it does not crash if I do not use an optional for the value-property. To me this looks like a bug in Swift's constructor code, but maybe I am overlooking something?
1
1
1.2k
Sep ’23
FileManager displayName(atPath:) no effect?
I logged in to macOS with my localization language. try to perform following code. but always get "Documents". What do I miss? Apple Swift version 5.2.4 macOS 10.15.6 Xcode 11.6 code let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) if paths.count &gt; 0 {     let doc = FileManager().displayName(atPath: paths[0])     print(doc) } result Documents
3
0
749
Jul ’23
SwiftUI negative kerning cuts off font
Hey there! Got a question about font kerning: When adding a negative kerning to a text (changes via user input) the last character sometimes gets cut off: dropbox.com/s/49ucdzk8m4k61sj/fontproblem1.png?dl=0 dropbox.com/s/vmklvxp510wjeak/fontproblem2.png?dl=0 What i do is the following: Text("\(pos, specifier: "%.1f")") &#9;.font(.system(size: 100,design: .serif)) &#9;.fontWeight(.bold) &#9;.kerning(-5) When i remove the kerning it works, but as i understood the kerning keeps the letters as they are? Is there an alternative way of doing it?
2
0
799
Apr ’24
Using UNNotificationServiceExtension with FCM not getting called
I don't know what could be wrong but my UNNotificationServiceExtension is never getting called by any push from FCM. I call the FCM from a Python3 script and so far it works (I get a push notification but always with the default text and not the modified one). firebaseHeaders = { "Content-Type":"application/json", "Authorization":"key=MYKEY" } firebaseBody = { "to":devicetoken, "priority":"high", "mutable-content":True, "apns-priority":5, "notification": { "titlelockey":"push.goalReachedTitle", "bodylockey":"push.goalReachedContentRemote", "bodylocargs":[str(entry['value']), entry['region']], "sound":"default", "badge":1 }, "data": { "values":data, "region":entry['region'], "value":entry['value'] } } firebaseResult = requests.post("https://fcm.googleapis.com/fcm/send", data=None, json=firebaseBody, headers=firebaseHeaders) My Extension is also pretty basic (for testing) and I already tried to remove it and add it again to my main app project without success. class NotificationService: UNNotificationServiceExtension { var contentHandler: ((UNNotificationContent) -> Void)? var bestAttemptContent: UNMutableNotificationContent? override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) { self.contentHandler = contentHandler bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent) if let bestAttemptContent = bestAttemptContent { bestAttemptContent.title = bestAttemptContent.title + " [TEST 123]" contentHandler(bestAttemptContent) } } override func serviceExtensionTimeWillExpire() { // Called just before the extension will be terminated by the system. // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used. if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent { contentHandler(bestAttemptContent) } } } Anyone has a idea what I still can check, test or miss?
7
2
6.6k
Sep ’23
Invalid code signature problem with Xcode12
I'm practicing a swift 5 class, and have this issue: Could not launch “I AM RICH” Domain: IDEDebugSessionErrorDomain Code: 3 Failure Reason: The operation couldn’t be completed. Unable to launch com.superdie.I-AM-RICH because it has an invalid code signature, inadequate entitlements or its profile has not been explicitly trusted by the user. User Info: {     DVTRadarComponentKey = 855031;     RawLLDBErrorMessage = "The operation couldn\U2019t be completed. Unable to launch com.superdie.I-AM-RICH because it has an invalid code signature, inadequate entitlements or its profile has not been explicitly trusted by the user."; } I'm not sure what can I do, some help would be nice :)
24
5
51k
Aug ’23
Facing compilation errors if I call variable argument C++ API from swift lang
I have an API with variable arguments in C++ library. I am trying to call this API from swift language. But I am facing with compilation errors as below. If I tried by removing variable arguments from the API then it is compiling. Please help to fix the error with variable arguments. API is void netops_log(enum log_level loglevel, const char *format, ...); Compilation errors: FilterDataProvider.swift:73:9: error: 'netops_log' is unavailable: Variadic function is unavailable     netops_log(LOGLEVEL_DEBUG, "Starting the filter... from NE")     ^~~~~~~~~~~~ __ObjC.netops_log:2:13: note: 'netops_log' has been explicitly marked unavailable here public func netops_log(_ loglevel: log_level, _ format: UnsafePointer<Int8>!, _ varargs: Any...)       ^
2
0
997
Oct ’23
Voice Over accessibility: UITableView
In our app, we display contacts in UITableView. Let us say I have 300 contacts in my AddressBook, and all of them will be displayed in this table. Below this table, I have a UIButton to perform some action like invite selected contacts. With Voice Over enabled, when I get to the UITableView, it doesn't let me to proceed to the UIButton, unless I go over all 300 contacts. Is there a solution to override this and make it more friendly to the visually impaired users?
2
0
3k
Aug ’23
GameCenter scores are not being posted to the leaderboard
Hello! Bare with me here, as there is a lot to explain! I am working on implementing a Game Center high score leaderboard into my game. I have looked around for examples of how to properly implement this code, but have come up short on finding much material. Therefore, I have tried implementing it myself based off information I found on apples documentation. Long story short, I am getting success printed when I update my score, but no scores are actually being posted (or at-least no scores are showing up on the Game Center leaderboard when opened). Before I show the code, one thing I have questioned is the fact that this game is still in development. In AppStoreConnect, the status of the leaderboard is "Not Live". Does this affect scores being posted? Onto the code. I have created a GameCenter class which handles getting the leaderboards and posting scores to a specific leaderboard. I will post the code in whole, and will discuss below what is happening. PLEASE VIEW ATTACHED TEXT TO SEE THE GAMECENTER CLASS! GameCenter class - https://developer.apple.com/forums/content/attachment/0dd6dca8-8131-44c8-b928-77b3578bd970 In a different GameScene, once the game is over, I request to post a new high score to Game Center with this line of code: GameCenter.shared.submitScore(id: GameCenterLeaderboards.HighScore.rawValue) Now onto the logic of my code. For the longest time I struggled to figure out how to submit a score. I figured out that in Xcode 12, they deprecated a lot of functions that previously worked for me. Not is seems that we have to load all leaderboards (or the ones we want). That is the purpose behind the leaderboards private variable in the Game Center class. On the start up of the app, I call authenticate player. Once this callback is reached, I call loadLeaderboards which will load the leaderboards for each string id in an enum that I have elsewhere. Each of these leaderboards will be created as a Leaderboard object, and saved in the private leaderboard array. This is so I have access to these leaderboards later when I want to submit a score. Once the game is over, I am calling submitScore with the leaderboard id I want to post to. Right now, I only have a high score, but in the future I may add a parameter to this with the value so it works for other leaderboards as well. Therefore, no value is passed in since I am pulling from local storage which holds the high score. submitScore will get the leaderboard from the private leaderboard array that has the same id as the one passed in. Once I get the correct leaderboard, I submit a score to that leaderboard. Once the callback is hit, I receive the output "Successfully submitted score to leaderboard". This looks promising, except for the fact that no score is actually posted. At startup, I am calling updatePlayerHighScore, which is not complete - but for the purpose of my point, retrieves the high score of the player from the leaderboard and is printing it out to the console. It is printing out (0), meaning that no score was posted. The last thing I have questions about is the context when submitting a score. According to the documentation, this seems to just be metadata that GameCenter does not care about, but rather something the developer can use. Therefore, I think I can cross this off as causing the problem. I believe I implemented this correctly, but for some reason, nothing is posting to the leaderboard. This was ALOT, but I wanted to make sure I got all my thoughts down. Any help on why this is NOT posting would be awesome! Thanks so much! Mark
6
1
3.4k
Mar ’24
How to prevent WKWebView open instagram app automatically?
I have been struggling to prevent WkWebView open Instagram app automatically when a user clicked a hyperlink on WKWebView. Currently, my app is able to open the new window/new tab request from my web app and load into a new ViewController which creating another WKWebView to handle the request. However, whenever I clicked the link which is opening the user's Instagram profile, iPhone will automatically open the installed Instagram app. I have tried a few approaches and it is still not working as expected. I have another social media app which is Facebook and it is working as expected because it doesn't open the installed Facebook app on my phone and able to load into the new ViewController. Scenario 1: Although able to open a new tab, but the entire webview has stopped working. Scenario 2: Unlimited loop due to will always trigger the decidePolicyFor function. Scenario 3: Delete installed Instagram app, It wouldn't open the app automatically and able to load into the local WkWebView but this is not the solution. Thank you in advance and sorry if I didn't provide a clear description. func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { &#9;&#9;if let host = navigationAction.request.url?.host { &#9;&#9;&#9; if host == "www.instagram.com" { &#9;&#9;&#9;&#9;&#9;&#9;&#9; &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;/* Scenario 2, unlimited loop */ &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;if let url = navigationAction.request.url { &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;let request = URLRequest(url: url) &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;self.webView.load(request) &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;} &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9; &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;/* Scenario 1, prevent loading user's instagram profile in local wkwebview */ &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;decisionHandler(.cancel) &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;return &#9;&#9;&#9;&#9;&#9;&#9;} &#9;&#9;&#9;&#9;} &#9; decisionHandler(.allow) }
3
0
2.7k
Sep ’23
ChildView in FullScreenCover is recreated every time if ContentView is updated
Hi guys. I have a question related to the next behavior. I have ContentView with a list of views where the corresponding view models are passed. The user can click by some view. At the moment full-screen modal dialog will be shown according to the passed type. It's fine. At some time my view models are being updated and the whole ContentView will be reloaded. The problem is: fullScreenCover is called and ChildEventView is recreated. How to prevent recreating ChildEventView? struct ContentView: View { &#9;&#9;@ObservedObject private var eventListViewModel = EventListViewModel() &#9;&#9;@State private var fullScreenType: FullScreenType? &#9;&#9;/* some stuff */ &#9;&#9;var body: some View { &#9;&#9;&#9;&#9;ScrollView { &#9;&#9;&#9;&#9;&#9;&#9;LazyVStack { &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;ForEach(eventListViewModel.cardStates.indices, id: \.self) { index in &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;let eventVM = eventListViewModel.eventVMs[index] &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;EventCardView(eventViewModel: eventVM, eventId: $selectedEvent.eventId) { &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;self.fullScreenType = .type1 &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;} &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;/* some other views */ &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;} &#9;&#9;&#9;&#9;&#9;&#9;} &#9;&#9;&#9;&#9;}&#9; &#9;&#9;&#9;&#9;.fullScreenCover(item: $fullScreenType, onDismiss: { &#9;&#9;&#9;&#9;&#9;&#9;self.fullScreenType = nil &#9;&#9;&#9;&#9;}, content: { fullScreenType in &#9;&#9;&#9;&#9;&#9;&#9;switch fullScreenType { &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;case .type1: &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;return ChildEventView(selectedEvent.eventId).eraseToAnyView() &#9;&#9;&#9;&#9;&#9;&#9;&#9;&#9;/* some other cases */ &#9;&#9;&#9;&#9;&#9;&#9;} &#9;&#9;&#9;&#9;}) &#9;&#9;} }
2
0
1.2k
Aug ’23
No such module 'Alamofire' while running simulator in Xcode 12.4
I have tried all below points to rectify this issue for ios 12 version in Xcode 12.4 but still not able to resolve this issue. I have uninstalled all pods and install updated pods Clean Project &amp; re-build Project Closed Xcode &amp; reopen the same. Turned OFF mac &amp; restarted. I also assure that I am opening xcworkspace project not xcodeproj. Kindly suggest anyone who faced same issue or rectified this issue or know how to resolve it.
5
0
7.3k
Jul ’23
How to get images that are in iCloud with PHPickerViewController?
I have been searching high and low for anyone that has encountered the same issue, My problem is when an image is not actually on the device but rather in iCloud, my app fails to retrieve the image. How would i go about remedying this? My code for PHPicker implementation is as follows, any help would be greatly appreciated. extension PageViewController: PHPickerViewControllerDelegate {       func presentPicker() {     ArtModel.holdingBay.removeAll()     var configuration = PHPickerConfiguration()     configuration.filter = .images     configuration.selectionLimit = 5     let picker = PHPickerViewController(configuration: configuration)     picker.delegate = self     present(picker, animated: true)   }       func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {     if results.count 0 {       for result in results {         result.itemProvider.loadObject(ofClass: UIImage.self, completionHandler: { (object, error) in           if let image = object as? UIImage {             DispatchQueue.main.async {               ArtModel.holdingBay.append(image)             }           }         })       }     }     picker.dismiss(animated: true, completion: self.holdingBayCheck)   }       func holdingBayCheck() {     if ArtModel.holdingBay.count 0 {       performSegue(withIdentifier: K.goToCrop, sender: self)     }   }     }
2
1
1.6k
Oct ’23
Simultaneously interacting with SwiftUI View below a UIViewRepresentable
My problem I have a SwiftUI app that uses PKCanvasView to allow drawing. The PKCanvasView is transparent and there are SwiftUI views (e.g. an Image) behind which can be dragged and opened. I want the user to be able to draw on the PKCanvasView with their apple pencil and interact with the views below with their finger... I can't figure out how to enable simultaneous interaction with the PKCanvasView (i.e. if using apple pencil draw) and the swiftUI views behind (i.e. if using finger, drag and move views). The context Here is my PKCanvasView wrapped in a UIViewRepresentable struct: struct CanvasView: UIViewRepresentable { @Binding var canvasView: PKCanvasView @State var toolPicker = PKToolPicker() func makeUIView(context: Context) - PKCanvasView { canvasView.drawingPolicy = .pencilOnly canvasView.backgroundColor = .clear canvasView.isOpaque = false canvasView.alwaysBounceVertical = true canvasView.alwaysBounceHorizontal = true toolPicker.setVisible(true, forFirstResponder: canvasView) toolPicker.addObserver(canvasView) return canvasView } func updateUIView(_ uiView: PKCanvasView, context: Context) { } } The structure of my content view is as follows: swift ZStack(alignment: .topLeading){                 CanvasView(canvasView: $canvasView)                     .zIndex(0)                 ForEach(canvas.subCanvases.indices, id: \.self){ index in                         CanvasCardView(                             canvas: $canvas.subCanvases[index],                             animationNamespace: animationNamespace,                             onReorder: {                                 reorderCard(at: canvas.subCanvases[index].zOrder)                         })                 }             } The CanvasCardView are the background SwiftUI views which can be dragged and opened. The view attaches a negative zIndex to them which orders them behind the CanvasView (PKCanvasView). My attempts I've tried two approaches so far which don't work: Subclassing PKCanvasView to override point(inside:with:). Passing false when I want to touches to be passed through. Problem with this is that the swiftUI views never recognise the touches through the UIView. I assume as there are no UITouchs behind the scenes. Adding a @State property to my contentView that can update an allowsHitTesting() modifier dynamically when required. The issue with this is that without allowing the PKCanvasView to be "hit" I can't determine whether it is a pencil touch or not. So i can't properly interact with PKCanvasView simultaneously. Any other ideas if this is possible? That is, passing touches through a UIViewRepresentable dynamically? I really want to avoid shoving the SwiftUI views into a UIView (with UIHostingController) and then turning them back into SwiftUI. Many thanks!
3
2
2.1k
Jul ’23
Instruments: why? “Failed to gain authorization”
I have a swift 5.4 package manager project with an executable target I want to profile in Instruments. I Cmd+I to profile which launches instruments. I pick allocations. then push the record button. im asked to authorise and doesn’t matter whether I use fingerprint or password I always get the error: (before run started) Failed to gain authorization any ideas? instruments 12.5 xcode 11.5 swift 5.4 2020 M1 MBP 13”
10
3
7.6k
Oct ’23