Build, test, and submit your app using Xcode, Apple's integrated development environment.

Posts under Xcode tag

200 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

Building Issue
Hello, I am very new to programming with Xcode. I’ve been searching the forums and online but can’t seem to find an answer. My project is not displaying the triangle build button in the left corner, nor the status of the build. No issues with my code are apparent, yet it does not build and preview when I push build and clean in the product tab
1
0
248
Dec ’24
Xcode 16 Minimum Deployments value Not Saving
Dear Apple Developer Support, I’m reporting an issue in Xcode 16 where the iOS minimum Deployments value in the Targets General tab resets to blank when set below iOS 15.6. This issue does not occur when setting the target through Build Settings, where it’s retained correctly. Steps to Reproduce: Set the minimum Deployments value to below 15.6 in General > minimum Deployments. Save and close the project. Reopen the project and check the target in General — it’s blank. Workarounds Tried: Tested on Xcode 16, 16.1, and 16.2. Manually set the target every time. Set the target via Build Settings (works but is inconvenient). System Info: Xcode: 16.2 macOS: 14.5 This impacts my workflow as my project targets iOS 13. Please investigate and advise. Please check the attached screenshots Thanks and Regards, Pavan
2
2
960
Dec ’24
Help needed to understand the issues from the app
Hi, There are total three errors from the app running on the device. First one is right after the app starts running on the device: Could not create a sandbox extension for '/var/containers/Bundle/Application/D4CBF093-EFB1-43C5-996D-7D5CB04BF643/appadmob.app' Below second issue comes when I dismiss the Interstitial Ad First responder issue detected: non-key window attempting reload - allowing due to manual keyboard (first responder window is <UIWindow: 0x10d11c700; frame = (0 0; 414 896); hidden = YES; autoresize = W+H; gestureRecognizers = <NSArray: 0x301749300>; backgroundColor = <UIDynamicSystemColor: 0x3002b3080; name = _windowBackgroundColor>; layer = <UIWindowLayer: 0x3019b7960>>, key window is <QUIWindow: 0x10880db00; baseClass = UIWindow; frame = (0 0; 414 896); gestureRecognizers = <NSArray: 0x3017276e0>; layer = <UIWindowLayer: 0x3019852f0>>) And the third issue below follows right after the second one: Error acquiring assertion: <Error Domain=RBSServiceErrorDomain Code=1 "((target is not running or doesn't have entitlement com.apple.developer.web-browser-engine.rendering AND target is not running or doesn't have entitlement com.apple.developer.web-browser-engine.networking AND target is not running or doesn't have entitlement com.apple.developer.web-browser-engine.webcontent))" UserInfo={NSLocalizedFailureReason=((target is not running or doesn't have entitlement com.apple.developer.web-browser-engine.rendering AND target is not running or doesn't have entitlement com.apple.developer.web-browser-engine.networking AND target is not running or doesn't have entitlement com.apple.developer.web-browser-engine.webcontent))}> 0x118024480 - ProcessAssertion::acquireSync Failed to acquire RBS assertion 'WebProcess NearSuspended Assertion' for process with PID=19180, error: (null) Failed to terminate process: Error Domain=com.apple.extensionKit.errorDomain Code=18 "(null)" UserInfo={NSUnderlyingError=0x3019254a0 {Error Domain=RBSRequestErrorDomain Code=3 "No such process found" UserInfo={NSLocalizedFailureReason=No such process found}}} Also when I dismissed the interstitial ad, the screen looks greyed out, but when I touch the screen, the screen comes to normal. Could you please suggest any solution for the problems. Thanks,
2
0
2.7k
Dec ’24
I would like to know how to switch the code view between Release and Debug modes.
You can see: in the first image, the default project have DEBUG macro. So in perview, release code segment is grey. But!!! In edit scheme, I change all of item to release mode! (See second image) At this point, the DEBUG code block is still highlighted. If I compile and run it, the output is actually from the Release code block. In other words, I have changed all the modes in the scheme, but the preview mode is still in DEBUG.
0
0
215
Dec ’24
Download Old version of Xcode
How can I save an Xcode project in Sequoia writen in Xcode Sequoia - Version 15.1 so that it can be opened in Ventura - Version 14.3.1 (14E300c) or in Big Sur Version 13.1 The error I get says Project.xcodeproj cannot be opened because it is in a future Xcode project file format. Adjust the project format using a compatible version of Xcode to allow it to be opened by this version of Xcode
1
0
540
Dec ’24
Passing data from a Finder Sync Extension to my main Swift app
Hi all, I am creating an app that, when you right-click on a file and select a custom option in the context menu, it pops open a window then processes this file. Currently, I am writing that file name and path to a plist in my app's group container folder, sending a notification from my finder sync extension to my main app, and then reading the values in my plist. Is this the best way to pass data between the finder sync extension and the main app? What is the industry standard way of doing this? Thanks, James
0
1
428
Dec ’24
Struggling with async/await: Fetching an image off the main thread
Hey everyone, I’m learning async/await and trying to fetch an image from a URL off the main thread to avoid overloading it, while updating the UI afterward. Before starting the fetch, I want to show a loading indicator (UI-related work). I’ve implemented this in two different ways using Task and Task.detached, and I have some doubts: Is using Task { @MainActor the better approach? I added @MainActor because, after await, the resumed execution might not return to the Task's original actor. Is this the right way to ensure UI updates are done safely? Does calling fetchImage() on @MainActor force it to run entirely on the main thread? I used an async data fetch function (not explicitly marked with any actor). If I were to use a completion handler instead, would the function run on the main thread? Is using Task.detached overkill here? I tried Task.detached to ensure the fetch runs on a non-main actor. However, it seems to involve unnecessary actor hopping since I still need to hop back to the main actor for UI updates. Is there any scenario where Task.detached would be a better fit? class ViewController : UIViewController{ override func viewDidLoad() { super.viewDidLoad() //MARK: First approch Task{@MainActor in showLoading() let image = try? await fetchImage() //Will the image fetch happen on main thread? updateImageView(image:image) hideLoading() } //MARK: 2nd approch Task{@MainActor in showLoading() let detachedTask = Task.detached{ try await self.fetchImage() } updateImageView(image:try? await detachedTask.value) hideLoading() } } func fetchImage() async throws -> UIImage { let url = URL(string: "https://via.placeholder.com/600x400.png?text=Example+Image")! //Async data function call let (data, response) = try await URLSession.shared.data(from: url) guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else { throw URLError(.badServerResponse) } guard let image = UIImage(data: data) else { throw URLError(.cannotDecodeContentData) } return image } func showLoading(){ //Show Loader handling } func hideLoading(){ //Hides the loader } func updateImageView(image:UIImage?){ //Image view updated } }
5
0
1.2k
Jan ’25
Your browser preventing this app to open “URL”
Hi Apple developers, I am very new to XCode and Swift, I am planning to build an app for iOS from a web. I tried to use WKWebView to handle the web , I managed to redirect some of the links to Safari, however some button/links didn't trigger .linkActivated function and encounter the error as "Your browser preventing this app to open “URL”. If I copy the URL to Safari is able to open, I trying to research on web but can't find any related solution for my case. Here is the code in my app: import UIKit import WebKit import SafariServices class ViewController: UIViewController, WKNavigationDelegate { var webView: WKWebView! override func viewDidLoad() { super.viewDidLoad() // Initialize WKWebView let webConfiguration = WKWebViewConfiguration() //enable javascript webConfiguration.preferences.javaScriptEnabled = true webView = WKWebView(frame: self.view.frame, configuration: webConfiguration) webView.navigationDelegate = self self.view.addSubview(webView) // Load a web page as webview if let url = URL(string: "https://myurl") { let request = URLRequest(url: url) webView.load(request) } //console log webView.evaluateJavaScript("console.log('Button clicked!')") { result, error in if let error = error { print("Error executing JavaScript: \(error.localizedDescription)") } else { print("JavaScript result: \(String(describing: result))") } } } func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { if let url = navigationAction.request.url, navigationAction.navigationType == .linkActivated { // Check if URL is external and open it in Safari if UIApplication.shared.canOpenURL(url) { UIApplication.shared.open(url, options: [:], completionHandler: nil) decisionHandler(.cancel) // Prevent loading the link in the WebView } else { decisionHandler(.allow) // Allow loading if URL cannot be opened in Safari } } else { decisionHandler(.allow) // Allow the WebView to load the URL normally } } }
1
0
698
Jan ’25
xcode quits unexpectedly every time i open it
computer specs: MacBook Pro 14in 2023 m2 pro 16gb macos ver: Version 15.1 Beta (24B5009l) Issue: When I open xcode on my Mac, it unexpectedly quits every time. I have disabled internet connection, it doesn't work. I have uninstalled and install again on appstore, it still doesn't work. I've open the app in another user on my laptop, it doesn't work. The problem report generated from the quitting Xcode is too long so i put it into the attached text file: Report Log when it reported quit unexpectedly
3
0
486
Dec ’24
Adding a sandboxed v2ray precompiled binary to my application
Greetings! I want to add my pre-compiled binary of v2ray to my application so I can activate it in background as a proxy and run stuff through it. I've codesigned it via: codesign -s - -i production.myproject.v2ray -o runtime --entitlements v2ray.entitlements -f v2ray Contents of entitlements file: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>com.apple.security.app-sandbox</key> <true/> <key>com.apple.security.files.downloads.read-write</key> <true/> <key>com.apple.security.files.user-selected.read-write</key> <true/> <key>com.apple.security.network.client</key> <true/> <key>com.apple.security.network.server</key> <true/> </dict> </plist> Originally I ran it like this without sandboxing from my main target app: guard let v2rayPath = Bundle.main.path(forResource: "v2ray", ofType: nil) else { throw NSError(domain: "ProxyController", code: 1, userInfo: [NSLocalizedDescriptionKey: "V2Ray binary not found in bundle"]) } let task = Process() task.executableURL = URL(fileURLWithPath: v2rayPath) task.arguments = ["-config", configURL.path] // Redirect output for debugging let pipe = Pipe() task.standardOutput = pipe task.standardError = pipe``` And it ran flawlessly. Now it refuses to start. Any help, pointers or examples of such usage will be greatly appreciated
2
0
602
Dec ’24
Xcode 16.x project doesn’t build with (SiriKit / Widget) intent definition file + translations
If you add a (SiriKit / Widget) intent definition file to an Xcode project and then translate it into another language, the build of the iOS app only works until you close the project. As soon as you open the project again, you get the error message with the next build: Unexpected duplicate tasks A workaround for this bug is, that you convert the folder (where the intent file is located) in Xcode to a group. After that every thing works without problems. Steps to reproduce: Create a new iOS project Add a localization to the project (German for example) Add a SiriKit Intent Definition File Localize the SiriKit Intent Definition File Build the project (should work without errors) Close the project Open the project again Build the project again Expected result: The project builds without problems Current result: The project doesn’t build and returns the error: Unexpected duplicate tasks Is this a known problem? Is there a way to solve this without switching to Xcode groups (instead of folders)
3
1
750
Dec ’24
Regarding the display of AppleArcade access points when playing iOS apps on visionOS.
[The problem that is occurring] The game apps in development are compatible with iOS, macOS, tvOS, and visionOS. In the Game app under development, the AppleArcade access point is placed in the main menu. In visionOS, when the main menu is opened, the GameCenter dashboard is automatically launched within 1~2 seconds after the main menu is displayed. This condition occurs every time the menu is re-opened. On iOS, macOS, and tvOS, the dashboard appears after pressing the GameCenter access point icon. [What you want to solve] We would like to make it so that the Game Center dashboard is launched after the access point icon is pressed on visionOS as it is on other operating systems. Or, if there is a standard implementation method for visionOS, please let us know.
1
0
508
Dec ’24
Converting FastAI Cat vs Dog Model into Core ML
FB:FB16079804 Hello, I've made the FastAI's Cat vs Dog model into model that distinguishes lemons from limes and it all works fine in a notebook. I am now looking to transform this model into Core ML for my iOS app using TorchScript and Apple official guidelines for coremltools. Model converts but I cannot see the Preview Tab in. Xcode. Have anyone of you tried to convert to Core ML? I guess my input types are not matching with coremltools expectations for preview but I am stuck . Here is my code. import torch import coremltools as ct from fastai.vision.all import * import json from torchvision import transforms # Load your Fastai model (replace with your actual path) learn = load_learner('lemonmodel.pkl') # Example input image (you can use any image from your dataset) input_image = PILImage.create('example.jpg') # Preprocess the image (assuming you used these transforms during training) to_tensor = transforms.ToTensor() normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) input_tensor = to_tensor(input_image) input_tensor = normalize(input_tensor) # Apply normalization # Add a batch dimension input_tensor = input_tensor.unsqueeze(0) # Ensure float32 type input_tensor = input_tensor.float() # Trace the model trace = torch.jit.trace(learn.model, input_tensor) # Define the Core ML input type (considering your model's input shape) _input = ct.ImageType( name="input_1", shape=input_tensor.shape, bias=[-0.485/0.229, -0.456/0.224, -0.406/0.225], scale=1./(255*0.226) ) # Convert the model to Core ML format mlmodel = ct.convert( trace, inputs=[_input], minimum_deployment_target=ct.target.iOS14 # Optional, set deployment target ) # Set model type as 'imageClassifier' for the Preview tab mlmodel.type = 'imageClassifier' # Correct structure for preview parameters** (assuming two classes: 'lemon' and 'lime') labels_json = { "imageClassifier": { "labels": ["lemon", "lime"], "input": { "shape": list(input_tensor.shape), # Provide the actual input shape "mean": [0.485, 0.456, 0.406], # Match normalization mean "std": [0.229, 0.224, 0.225] # Match normalization std }, "output": { "shape": [1, 2] # Output shape for your model (2 classes) } } } # Setting up the metadata with correct 'preview' params mlmodel.user_defined_metadata['com.apple.coreml.model.preview.params'] = json.dumps(labels_json) # Save the model as .mlmodel mlmodel.save("LemonClassifierGemini.mlmodel") mlmodel = ct.convert( trace, inputs=[_input], minimum_deployment_target=ct.target.iOS14 # Optional, set deployment target ) # Set model type as 'imageClassifier' for the Preview tab** mlmodel.type = 'imageClassifier' # Correct structure for preview parameters** (assuming two classes: 'lemon' and 'lime') labels_json = { "imageClassifier": { "labels": ["lemon", "lime"], "input": { "shape": list(input_tensor.shape), # Provide the actual input shape "mean": [0.485, 0.456, 0.406], # Match normalization mean "std": [0.229, 0.224, 0.225] # Match normalization std }, "output": { "shape": [1, 2] # Output shape for your model (2 classes) } } } # Setting up the metadata with correct 'preview' params** mlmodel.user_defined_metadata['com.apple.coreml.model.preview.params'] = json.dumps(labels_json) # Save the model as .mlmodel mlmodel.save("LemonClassifierGemini.mlmodel") My model is : Input batch shape: torch.Size([32, 3, 192, 192]) Labels batch shape: torch.Size([32]) Validation Loss: None, Validation Metric: None Predictions shape: torch.Size([63, 2]) Targets shape: torch.Size([63]) Code for the model : searches = 'lemon','lime' path = Path('lemon_or_not') for o in searches: dest = (path/o) dest.mkdir(exist_ok=True, parents=True) download_images(dest, urls=search_images(f'{o} photo')) time.sleep(5) resize_images(path/o, max_size=400, dest=path/o) dls = DataBlock( blocks=(ImageBlock, CategoryBlock), get_items=get_image_files, splitter=RandomSplitter(valid_pct=0.2, seed=42), get_y=parent_label, item_tfms=[Resize(192, method='squish')] ).dataloaders(path, bs=32) dls.show_batch(max_n=6) learn = vision_learner(dls, resnet18, metrics=error_rate) learn.fine_tune(3) is_lemon,_,probs = learn.predict(PILImage.create('lemon.jpg')) print(f"This is a: {is_lemon}.") print(f"Probability it's a lemon: {probs[0]:.4f}") This is a: lemon. Probability it's a lemon: 1.0000 learn.export('lemonmodel.pkl') I am stuck to why it doest show the Preview Tab.
3
0
702
Dec ’24
Moving files to local package not possible in Xcode 16?
Hi! Trying to move some code into a local package - with Xcode 16 I am unable to move my code to the new package as drag and drop will always result in a copy. This contradicts the demo in the original intro session at WWDC19, and also the current documentation.. Of course I can delete the original files but this feels somewhat wrong... Am I missing something? Did the behaviour of moving files in the Project navigator change in the recent Xcode releases?
0
0
293
Dec ’24
Assets.xcassets vs. Media.xcassets
In Xcode 16, when I use File > New > Project to create a new iOS app project, Xcode automatically creates an asset catalog file called Assets.xcassets in the project. However, if I later use File > New > File from Template, for example to add an asset catalog to an embedded Swift package within a project, Xcode suggests the default filename Media.xcassets for the file, instead of Assets.xcassets. Why is the default name for this file different in each context? Thank you for explaining this troubling consistency issue which causes me to lie awake at night.
1
0
522
Dec ’24
Is is possible to have environment variables in iOS, watchOS and tvOS? How does it work?
Hi, so a little context, by environment variables I mean like $HOME in linux. I know that there are some standard and some app specific environment variables in the above mentioned platforms. Is is possible for the user to set environment variables? If so, what are the ways in which users can set environment variables in the platforms mentioned across the system or for the app as they would in macOS/linux/windows? And is it possible for developers of the app do the same? If so how? What I have found so far is that it cannot be done by users, and there is one place in xcode where I, as a developer can set environment variables for my app from the scheme. This isn't available when I ship just the installation binary to the end user, but rather is available only when the app is run using xcode. I just need validation that what I understand is correct and that there aren't other ways to do this by the user/developer without jailbreaking.
1
0
445
Dec ’24
Xcode 16 Organizer Failed to Download Report's Stack Trace
I am currently investigating an issue with my app's slow launch time in Xcode 16. However, when I open the Launches pane in the Xcode Organizer, I can only see the report list, but I encounter an error message like the one below in the stack trace. This issue also occurs in the Disk Writes, Energy, and Hangs panes, but not in the Crashes pane. Can someone advise me on what steps I should take? Any help would be greatly appreciated.
1
0
470
Dec ’24
Xcode 16: SwiftUI plain Button & UIButton not working
It looks like Xcode 16 has changed this behavior so I'm not sure if this is a bug or not. When a SwiftUI Button wraps a UIButton, the button doesn't work on iOS 18.0+ import SwiftUI struct ContentView: View { var body: some View { VStack { Button(action: { print("Not called on iOS 18") }) { WrapperButton() .frame(width: 200, height: 50) } } } } struct WrapperButton: UIViewRepresentable { func makeUIView(context: Context) -> some UIView { let button = UIButton(type: .system) button.setTitle("OK", for: .normal) return button } func updateUIView(_ uiView: UIViewType, context: Context) {} } This occurs with the app build with Xcode 16 and running on iOS 18 but it was worked with Xcode 15 builds and running on iOS 18
1
0
537
Dec ’24
Modularizing an Xcode 16 project
My preferred way of setting up an app project no longer works in Xcode 16. I like to have my apps massively modularized - a separate SPM module for every significant feature. I use a project grouped together with a package that contains all the feature modules. The project's app target imports a consolidated AppFeature from the package that is all the logic of the app. In Xcode 15 and before, I had a process for creating this kind of setup (described below -- unfortunately the forums don't support collapsible sections). Where I used to be able to drag a directory from Finder into the Xcode files navigator (step 6 in my process), it now rejects the drag. What I'm looking for is a way to have a single window open that has my Swift package and below that a separate folder for each executable target. Creating new modules in the package automatically creates new schemes in Xcode. Executable targets in the project can reference any module in the package. Source control treats the entire thing as one repository. I've tried all the approaches I can think of to accomplish the same goal, but no luck. The projects I've already built work fine in Xcode 16 -- I just can't make a new one. Unfortunately I can't revert to Xcode 15 for this purpose since it apparently doesn't run on my work machine with macOS 15. Here's my process that worked great till now: In Terminal, create the project folder Foo: $ mkdir Foo $ cd Foo Create the package: $ swift package init Creating library package: Foo Creating Package.swift ... Create a directory for the project: $ mkdir App In Xcode, create a new app project called Foo and put it in the App folder Open the Foo project Drag the top level Foo directory from Finder into the Xcode project and drop it immediately under the project name Close the Xcode project Create a file called Package.swift and place it in the App folder. Edit it to have an empty package content. This ensures Xcode won’t display that folder in the source navigator under the package header. import PackageDescription let package = Package( name: "", products: [], dependencies: [], targets: [] ) Open the Xcode project. You should have top-level project name* Foo*. Under that will be the package, also named Foo. Then there will be the app target, also named Foo. You can rename the app target folder Foo to something like iOS if you want to have other targets for other platforms like macOS.
1
0
1.1k
Dec ’24