Discuss Swift.

Swift Documentation

Post

Replies

Boosts

Views

Activity

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
1k
Nov ’20
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
Dec ’20
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
Dec ’20
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
Apr ’21
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
May ’21
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.7k
Jun ’21
Rotating a page in a pdf file - and get a mirrored image
I try to rotate a page 180° in a pdf file. I nearly get it, but the page is also mirrored horizontally. Some images to illustrate: Initial page: Result after rotation (see code): it is rotated 180° BUT mirrored horizontally as well: The expected result It is just as if it was rotated 180°, around the x axis of the page. And I would need to rotate 180° around z axis (perpendicular to the page). It is probably the result of writeContext!.scaleBy(x: 1, y: -1) I have tried a lot of changes for transform, translate, scale parameters, including removing calls to some of them, to no avail. @IBAction func createNewPDF(_ sender: UIButton) { var originalPdfDocument: CGPDFDocument! let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) let documentsDirectory = urls[0] // read some pdf from bundle for test if let path = Bundle.main.path(forResource: "Test", ofType: "pdf"), let pdf = CGPDFDocument(URL(fileURLWithPath: path) as CFURL) { originalPdfDocument = pdf } else { return } // create new pdf let modifiedPdfURL = documentsDirectory.appendingPathComponent("Modified.pdf") guard let page = originalPdfDocument.page(at: 1) else { return } // Starts at page 1 var mediaBox: CGRect = page.getBoxRect(CGPDFBox.mediaBox) // mediabox which will set the height and width of page let writeContext = CGContext(modifiedPdfURL as CFURL, mediaBox: &mediaBox, nil) // get the context var pageRect: CGRect = page.getBoxRect(CGPDFBox.mediaBox) // get the page rect writeContext!.beginPage(mediaBox: &pageRect) let m = page.getDrawingTransform(.mediaBox, rect: mediaBox, rotate: 0, preserveAspectRatio: true) // Because of rotate 0, no effect ; changed rotate to 180, then get an empty page writeContext!.translateBy(x: 0, y: pageRect.size.height) writeContext!.scaleBy(x: 1, y: -1) writeContext!.concatenate(m) writeContext!.clip(to: pageRect) writeContext!.drawPDFPage(page) // draw content in page writeContext!.endPage() // end the current page writeContext!.closePDF() } Note: This is a follow up of a previous thread, https://developer.apple.com/forums/thread/688436
2
0
1.5k
Aug ’21
Type 'VNRecognizedPointKey' has no member 'thumbTip'
With the release of Xcode 13, a large section of my vision framework processing code became errors and cannot compile. All of these have became deprecated. This is my original code:  do {       // Perform VNDetectHumanHandPoseRequest       try handler.perform([handPoseRequest])       // Continue only when a hand was detected in the frame.       // Since we set the maximumHandCount property of the request to 1, there will be at most one observation.       guard let observation = handPoseRequest.results?.first else {         self.state = "no hand"         return       }       // Get points for thumb and index finger.       let thumbPoints = try observation.recognizedPoints(forGroupKey: .handLandmarkRegionKeyThumb)       let indexFingerPoints = try observation.recognizedPoints(forGroupKey: .handLandmarkRegionKeyIndexFinger)       let middleFingerPoints = try observation.recognizedPoints(forGroupKey: .handLandmarkRegionKeyMiddleFinger)       let ringFingerPoints = try observation.recognizedPoints(forGroupKey: .handLandmarkRegionKeyRingFinger)       let littleFingerPoints = try observation.recognizedPoints(forGroupKey: .handLandmarkRegionKeyLittleFinger)       let wristPoints = try observation.recognizedPoints(forGroupKey: .all)               // Look for tip points.       guard let thumbTipPoint = thumbPoints[.handLandmarkKeyThumbTIP],          let thumbIpPoint = thumbPoints[.handLandmarkKeyThumbIP],          let thumbMpPoint = thumbPoints[.handLandmarkKeyThumbMP],          let thumbCMCPoint = thumbPoints[.handLandmarkKeyThumbCMC] else {         self.state = "no tip"         return       }               guard let indexTipPoint = indexFingerPoints[.handLandmarkKeyIndexTIP],          let indexDipPoint = indexFingerPoints[.handLandmarkKeyIndexDIP],          let indexPipPoint = indexFingerPoints[.handLandmarkKeyIndexPIP],          let indexMcpPoint = indexFingerPoints[.handLandmarkKeyIndexMCP] else {         self.state = "no index"         return       }               guard let middleTipPoint = middleFingerPoints[.handLandmarkKeyMiddleTIP],          let middleDipPoint = middleFingerPoints[.handLandmarkKeyMiddleDIP],          let middlePipPoint = middleFingerPoints[.handLandmarkKeyMiddlePIP],          let middleMcpPoint = middleFingerPoints[.handLandmarkKeyMiddleMCP] else {         self.state = "no middle"         return       }               guard let ringTipPoint = ringFingerPoints[.handLandmarkKeyRingTIP],          let ringDipPoint = ringFingerPoints[.handLandmarkKeyRingDIP],          let ringPipPoint = ringFingerPoints[.handLandmarkKeyRingPIP],          let ringMcpPoint = ringFingerPoints[.handLandmarkKeyRingMCP] else {         self.state = "no ring"         return       }               guard let littleTipPoint = littleFingerPoints[.handLandmarkKeyLittleTIP],          let littleDipPoint = littleFingerPoints[.handLandmarkKeyLittleDIP],          let littlePipPoint = littleFingerPoints[.handLandmarkKeyLittlePIP],          let littleMcpPoint = littleFingerPoints[.handLandmarkKeyLittleMCP] else {         self.state = "no little"         return       }               guard let wristPoint = wristPoints[.handLandmarkKeyWrist] else {         self.state = "no wrist"         return       } ... } Now every line from thumbPoints onwards results in error, I have fixed the first part (not sure if it is correct or not as it cannot compile) to :         let thumbPoints = try observation.recognizedPoints(forGroupKey: VNHumanHandPoseObservation.JointsGroupName.thumb.rawValue)        let indexFingerPoints = try observation.recognizedPoints(forGroupKey: VNHumanHandPoseObservation.JointsGroupName.indexFinger.rawValue)        let middleFingerPoints = try observation.recognizedPoints(forGroupKey: VNHumanHandPoseObservation.JointsGroupName.middleFinger.rawValue)        let ringFingerPoints = try observation.recognizedPoints(forGroupKey: VNHumanHandPoseObservation.JointsGroupName.ringFinger.rawValue)        let littleFingerPoints = try observation.recognizedPoints(forGroupKey: VNHumanHandPoseObservation.JointsGroupName.littleFinger.rawValue)        let wristPoints = try observation.recognizedPoints(forGroupKey: VNHumanHandPoseObservation.JointsGroupName.littleFinger.rawValue) I tried many different things but just could not get the retrieving individual points to work. Can anyone help on fixing this?
2
0
1.6k
Sep ’21
Xcode 13 typing is delayed / really slow
I just updated Xcode to the newest Version (13.0 13A233). And what I immediately recognized was that when I was typing in a large class (1000 Lines or more) the typing was delayed like 1 or 2 seconds. This makes it really hard to type or even do anything with my project. It works perfectly fine in smaller projects with only 100 Code Lines per File, but it is really hard to type in bigger projects with over 30 files and 3000 Code Lines per File. This always happens when I use Xcode, whether I run the app on a real device or a simulator. Things that could cause the issue in my case: I removed the contents of ~/Library/Developer/Xcode/iOS DeviceSupport, because it took the device previously too long to launch, but I don´t think that this should have an effect on my Xcode typing performance. I would really appreciate any help, because this issue makes my work impossible and really concerns me a lot.
52
3
19k
Oct ’21
XPC, Swift, ObjC, and arrays
I create a protocol that had, among other things: @objc func setList(_: [MyType], withReply: @escaping (Error?) -> Void) The daemon part is in Swift, while the calling part is in Objective-C. Because why not? (Actually, because the calling part has to deal with C++ code, so that's ObjC++; however, I wanted the stronger typing and runtime checking for the daemon part, so I wrote it in Swift.) The ObjC part uses NSArray<MyType*>. I set up an NSXPCConnection link, and create a (synchronous) proxy with the right protocol name. But when I try to do the XPC setList call, I get an error. I assume that's because it doesn't like the signature. (Surely this is logged somewhere? I couldn't find it, if so. 😩) But... if I have a signature of @objc func addItem(_: MyType, withReply: @escaping (Error?) -> Void), then it works. So I assume it's the array. (Oh, I've also tried it without the @objc; the protocol itself is defined as @objc.) I've tried changing to protocol signature to using NSArray, but same thing.
7
0
1.1k
Dec ’21
Calling an environment variable from a .xcconfig file in swift
I'm trying to setup a GitHub repository for a project that will involve the use of an API Key. In order to keep that key a secret, I have decided to make a .xcconfig file with the API Key and add the .xcconfig file to my .gitignore. So far I have linked the file with my build settings for the app target. But I'm not actually sure how to go about calling the variable in my swift code. I know that there are environment variables within the Xcode build schemes, but I'm not sure how you would call them from there either. Is there some kind of framework that I need to call? Nothing online seems to be pointing to linking to the actual file itself.
3
1
5.8k
Feb ’22
WKWebView evaluateJavascript method crash with async/await when javascript call doesn't have return value
I wrote a code like the example below to execute javascript code that has no return value. let webView: WKWebView // after load complete let result = await webView.evaluateJavascript("someFunction()") // :0: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value but when i use method with completion handler manner, it doesn't be crashed. but Xcode enforces me to use 'await' keyword and warning is bordering me await webView.evaluateJavaScript("someFunction()", completionHandler: nil) // warning: Consider using asynchronous alternative function The differnce I found is the different signature. Completion handler version has Optional result type, but async/await version has just Any result type func evaluateJavaScript(_ javaScriptString: String, completionHandler: ((Any?, Error?) -> Void)? = nil) func evaluateJavaScript(_ javaScriptString: String) async throws -> Any my Xcode version is 13.2.1. Hope to fix it soon.
6
9
3.3k
Mar ’22
How to get the page URL shared via the Share button on macOS?
I have a macOS Share Extension invoked when users tap the Share button in Safari. I'm trying to get the page's URL from the -[NSExtensionItem attachments] attribute, but it comes as an NSSecureCoding object, and I'm unable to read the URL from it. In the loadView method, I'm filtering and loading the attachments of type public.url: override func loadView() { super.loadView() guard let inputItem = extensionContext?.inputItems.first as? NSExtensionItem else { print("Didn't received input item from action.") return } var itemProvider: NSItemProvider? itemProvider = inputItem.attachments?.filter({ $0.registeredTypeIdentifiers.contains("public.url") }).first ?? inputItem.attachments?.filter({ $0.registeredTypeIdentifiers.contains("public.plain-text") }).first guard let itemProvider = itemProvider else { print("Didn't received attachments from input item.") return } if itemProvider.canLoadObject(ofClass: URL.self) { itemProvider.loadItem(forTypeIdentifier: "public.url", completionHandler: onLoadVideoURL) } else if itemProvider.canLoadObject(ofClass: String.self) { itemProvider.loadItem(forTypeIdentifier: "public.plain-text", completionHandler: onLoadVideoURL) } else { print("This action only supports URL and String.") } } The itemProvider.loadItem method runs for the type identifier public.url, calling the completion handler bellow: @objc private func onLoadVideoURL(dict: NSSecureCoding?, error: Error?) { print("URL: \(dict.debugDescription)") // ... } But the content that it prints to the console is: URL: Optional(<68747470 733a2f2f 73746163 6b6f7665 72666c6f 772e636f 6d2f7175 65737469 6f6e732f 35323231 39373030 2f686f77 2d746f2d 63617374 2d6e7373 65637572 65636f64 696e672d 746f2d6d 6b6d6170 6974656d 2d696e2d 61637469 6f6e2d65 7874656e 73696f6e>) The same code works as expected on iOS, printing the shared URL to the console. Do I have to somehow convert this NSSecureCoding to URL or another object? Or should I do this in a completely different way on macOS? The goal is to access the page's URL from the Share Extension activated when the user selects it in the Share Menu.
2
0
2.1k
Mar ’22
Package pre build script execution
Hello, i am currently trying to implement a pre build script execution in a package. I am using this tutorial to implement it. But it only shows how to use the pre build feature with an already existing feature. I want to execute a skript on my pc every time i build the project. I can't use apples prebuild skript feature in the build settings because it is a package. Right now my code looks like this: import Foundation import OSLog import PackagePlugin @main struct GenerateLocalizer: BuildToolPlugin {     do {       let commandlineOutput = try shell("./testScript.sh")     } catch {     }     return [.prebuildCommand(displayName: "Generate Strings", executable: PackagePlugin.Path("./scrips/generate_strings.sh"), arguments: [], outputFilesDirectory: target.directory)]   }   func shell(_ command: String) throws -> String {     let task = Process()     let pipe = Pipe()     task.standardOutput = pipe     task.standardError = pipe     task.arguments = [command]     os_log("%{public}@", log: log, task.arguments?.joined(separator: " ") ?? "not found")     task.launchPath = "/bin/zsh"     task.standardInput = nil     try task.run()     let data = pipe.fileHandleForReading.readDataToEndOfFile()     let output = String(data: data, encoding: .utf8)!     return output   } } and my Package file looks something like that       name: "CustomSdk",       dependencies: ["CustomSdk-Objc"],       path: "CustomSdk",       exclude: ["Info.plist", "CustomSdk.podspec"],       plugins: [         .plugin(name: "GenerateLocalizer")       ]     ),     .plugin(name: "GenerateLocalizer",         capability: .buildTool(),         dependencies: ["CustomSdk-Objc"]     ) It gets called properly but when want to write files in my "testScript.sh" it only says: Operation not permitted. Anyone got any ideas how to fix this or is there another way to utitlize custom scripts with custom packages? Greetings Ben
2
1
2.6k
Jun ’22
Stripe Apple Pay Pod Error while building Flutter iOS App
I am facing this issue have a look please and help me fix it asap!!!! :( Swift Compiler Error (Xcode): '(any PKPaymentAuthorizationControllerDelegate) -> ((PKPaymentAuthorizationController, PKShippingMethod, @escaping (PKPaymentRequestShippingMethodUpdate) -> Void) -> Void)?' is not convertible to 'pkDidSelectShippingMethodSignature' (aka 'Optional<((PKPaymentAuthorizationControllerDelegate) -> (PKPaymentAuthorizationController, PKShippingMethod, @escaping (PKPaymentRequestShippingMethodUpdate) -> ()) -> ())>') /Users/apple/Desktop/Cool%20Panda%20Apps/provider_flutter/ios/Pods/StripeApplePay/StripeApplePay/StripeApplePay/Source/ApplePayContext/STPApplePayContext.swift:239:53 Screenshot: Deleted PODfile.lock and Pods folder millions of times and installed pods again. Still no luck same error!!! Here is the screenshot of the PODFILE:  P.S: Using Xcode 14.0(Beta) as I need to develop for iOS 16 as well. io
8
4
4.1k
Jun ’22