Dive into the world of programming languages used for app development.

All subtopics

Post

Replies

Boosts

Views

Activity

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) { 		if let host = navigationAction.request.url?.host { 			 if host == "www.instagram.com" { 							 								/* Scenario 2, unlimited loop */ 								if let url = navigationAction.request.url { 										let request = URLRequest(url: url) 										self.webView.load(request) 								} 								 								/* Scenario 1, prevent loading user's instagram profile in local wkwebview */ 								decisionHandler(.cancel) 								return 						} 				} 	 decisionHandler(.allow) }
3
0
2.7k
Dec ’20
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.8k
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.6k
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
iOS cpu/gpu/battery temperature readings
Good day! I'm interested in if there is any way to query CPU/GPU/Battery temperature values on recent iOS systems? I've tried to search forums for "cpu temp", "ios temperature", "battery temperature" etc., but didn't find anything. There was only mentioned some old private API which was supposed to work somehow for iOS&lt;10. All the examples I've found didn't even compile. All the requests and suggestions are pretty old and seems irrelevant. So I decided to bump this topic. Are there any updates? Any hints and suggestions are highly appreciated! Best regards!
4
0
5.3k
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.9k
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.
7
10
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
A bug in Xcode lldb debugger for swift
In some particular situation, Xcode debugger or lldb cli cannot correctly extract some value that returned by a async throw function and handled by guard let try?. Here is the minimum example: import Dispatch func test() async throws -> [Int] {   return [369] } let group = DispatchGroup() group.enter() let task = Task {   guard let res = try? await test() else { return }   print(res)   group.leave() } group.wait() If added a break point at print(res), the debugger cannot show the value of res. Due to forum limitation, I cannot paste a screenshot here... if use p res or po res at lldb cli, it shows: (lldb) p res error: expression failed to parse: error: <EXPR>:3:1: error: cannot find 'res' in scope res ^~~ (lldb) po res error: expression failed to parse: error: <EXPR>:3:1: error: cannot find 'res' in scope res ^~~ If test() returns a dict, or a costom struct, the issue retains. But if returned a trivial value like Int, it acts normally. Also, if remove the guard statement, make res a optional value(use let res = try? await test()), debugger can extract the value. Above results are compiled and run in this environment: Swift 5.6.1 Xcode 13.4.1 (13F100) lldb-1316.0.9.46 macOS 12.4 x86_64 arch
5
3
3.9k
Jul ’22