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

(tvOS) Categories or Selection Menus Don't Fit the Design
Hi everyone, I'm currently working on my own Apple TV app. So far, things are going pretty well, but right now, I'm stuck on the design of the categories or selection menus. Here's a screenshot of how it looks right now: The green color and the border are intentionally added for now so I can see what is where. My actual goal is to remove the gray bar (or is this the "main bar"?). The pink bar and its border are just design elements that can be removed if needed. I want it to look more "original," like this: Here is the code: let title: String let isSelected: Bool var body: some View { HStack { Text(title) .foregroundColor(isSelected ? .black : .white) .font(.system(size: 22, weight: .regular)) .padding(.leading, 20) Spacer() Image(systemName: "chevron.right") .foregroundColor(isSelected ? .black : .gray) .padding(.trailing, 20) } .frame(height: 50) // Einheitliche Höhe für die Kategorien .background(Color.pink) // Innerer Hintergrund auf pink gesetzt .cornerRadius(10) // Abrundung direkt auf den Hintergrund anwenden .overlay( RoundedRectangle(cornerRadius: 10) .stroke(Color.green, lineWidth: 3) // Äußerer Rahmen auf grün gesetzt ) .padding(.horizontal, 0) // Entferne äußere Ränder .background(Color.clear) // Entferne alle anderen Hintergründe } } struct SettingsView_Previews: PreviewProvider { static var previews: some View { SettingsView() } } I’ve adjusted the code, but it’s still not quite right. When a category is not selected, it appears black instead of gray, like in the original design Here is the code: struct SettingsView: View { @State private var selectedCategory: String? var body: some View { NavigationStack { ZStack { Color.black .edgesIgnoringSafeArea(.all) VStack(spacing: 0) { // Überschrift oben in der Mitte Text("Einstellungen") .font(.system(size: 40, weight: .semibold)) .foregroundColor(.white) .padding(.top, 30) HStack { // Linke Seite mit Logo VStack { Spacer() Image(systemName: "applelogo") .resizable() .scaledToFit() .frame(width: 120, height: 120) .foregroundColor(.white) Spacer() } .frame(width: UIScreen.main.bounds.width * 0.4) // Rechte Seite mit Kategorien VStack(spacing: 15) { ForEach(categories, id: \.self) { category in NavigationLink( value: category, label: { SettingsCategoryView( title: category, isSelected: selectedCategory == category ) } ) .buttonStyle(PlainButtonStyle()) } } .frame(width: UIScreen.main.bounds.width * 0.5) } } } .navigationDestination(for: String.self) { value in Text("\(value)-Ansicht") .font(.title) .foregroundColor(.white) .navigationTitle(value) } } } private var categories: [String] { ["Allgemein", "Benutzer:innen und Accounts", "Video und Audio", "Bildschirmschoner", "AirPlay und HomeKit", "Fernbedienungen und Geräte", "Apps", "Netzwerk", "System", "Entwickler"] } } struct SettingsCategoryView: View { let title: String let isSelected: Bool var body: some View { HStack { Text(title) .foregroundColor(.white) .font(.system(size: 22, weight: .medium)) .padding(.leading, 20) Spacer() Image(systemName: "chevron.right") .foregroundColor(.gray) .padding(.trailing, 20) } .frame(height: 50) // Einheitliche Höhe für die Kategorien .background(isSelected ? Color.gray.opacity(0.3) : Color.clear) // Hervorhebung des ausgewählten Elements .cornerRadius(8) // Abgerundete Ecken .scaleEffect(isSelected ? 1.05 : 1.0) // Fokus-Animation .animation(.easeInOut, value: isSelected) } } struct SettingsView_Previews: PreviewProvider { static var previews: some View { SettingsView() } }
0
0
528
Jan ’25
Persistent "Framework 'Flutter' Not Found" Error When Building iOS Simulator
I'm currently facing a recurring issue while attempting to build my Flutter app for the iOS simulator. The build process fails with the following error Error (Xcode): Framework 'Flutter' not found Error (Xcode): Linker command failed with exit code 1 Steps I've Taken: Recreated the ios/ folder and cleared derived data: Used flutter clean to clean the project. Reinstalled CocoaPods with pod deintegrate followed by pod install. Verified Configuration: Checked AppDelegate and framework paths within Xcode. Set the deployment target to 14.0 in the Podfile. Additional Actions: Performed flutter clean again, followed by removal of Pods, .symlinks, and Flutter.framework under ios/. Updated CocoaPods, ensured all dependencies in pubspec.yaml are current. Added FirebaseCore initialization in AppDelegate.swift to resolve previous Firebase integration issues. Despite these efforts, the "Framework 'Flutter' not found" error persists. Here's the relevant part of my AppDelegate.swift and Podfile: swift import Flutter import UIKit @main @objc class AppDelegate: FlutterAppDelegate { override func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { GeneratedPluginRegistrant.register(with: self) return super.application(application, didFinishLaunchingWithOptions: launchOptions) } } ruby platform :ios, '14.0' CocoaPods analytics sends network stats synchronously affecting flutter build latency. ENV['COCOAPODS_DISABLE_STATS'] = 'true' project 'Runner', { 'Debug' => :debug, 'Profile' => :release, 'Release' => :release, } def flutter_root generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), FILE) unless File.exist?(generated_xcode_build_settings_path) raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first" end File.foreach(generated_xcode_build_settings_path) do |line| matches = line.match(/FLUTTER_ROOT=(.*)/) return matches[1].strip if matches end raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get" end require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) flutter_ios_podfile_setup target 'Runner' do use_frameworks! use_modular_headers! flutter_install_all_ios_pods File.dirname(File.realpath(FILE)) target 'RunnerTests' do inherit! :search_paths end end post_install do |installer| installer.pods_project.targets.each do |target| flutter_additional_ios_build_settings(target) target.build_configurations.each do |config| xcconfig_path = config.base_configuration_reference.real_path xcconfig = File.read(xcconfig_path) xcconfig_mod = xcconfig.gsub(/DT_TOOLCHAIN_DIR/, "TOOLCHAIN_DIR") end end end Error Log from Flutter Run: [ +278 ms] Failed to build iOS app [ +42 ms] Error (Xcode): Framework 'Flutter' not found [ +8 ms] Error (Xcode): Linker command failed with exit code 1 (use -v to see invocation) [ +7 ms] Could not build the application for the simulator. [ +1 ms] Error launching application on iPhone 16 Pro Max. [ +6 ms] "flutter run" took 88,663ms. [ +164 ms] #0 throwToolExit (package:flutter_tools/src/base/common.dart:10:3) #1 RunCommand.runCommand (package:flutter_tools/src/commands/run.dart:860:9) #2 FlutterCommand.run. (package:flutter_tools/src/runner/flutter_command.dart:1450:27) #3 AppContext.run. (package:flutter_tools/src/base/context.dart:153:19) #4 CommandRunner.runCommand (package:args/command_runner.dart:212:13) #5 FlutterCommandRunner.runCommand. (package:flutter_tools/src/runner/flutter_command_runner.dart:421:9) #6 AppContext.run. (package:flutter_tools/src/base/context.dart:153:19) #7 FlutterCommandRunner.runCommand (package:flutter_tools/src/runner/flutter_command_runner.dart:364:5) #8 run.. (package:flutter_tools/runner.dart:131:9) #9 AppContext.run. (package:flutter_tools/src/base/context.dart:153:19) #10 main (package:flutter_tools/executable.dart:94:3) . Environment: Flutter: Version 3.27.3, Channel stable Xcode: Version 16.2, Build 16C5032a CocoaPods: Version 1.16.2 macOS: Version 15.2 (24C101) Additional Context: Initially, the issue was resolved by the sequence of cleanup and reinstalls listed above, but it re-emerged after integrating Firebase authentication. After adding FirebaseCore to AppDelegate.swift, the Firebase issue was resolved, but the framework error returned. I'm seeking guidance to resolve this issue permanently. Any insights or suggestions would be greatly appreciated!
1
0
970
Jan ’25
TipUIPopoverViewController can be referenced below iOS 17 without a compiler error and it shouldn't
We have found a runtime crash using TipUIPopoverViewController because Xcode didn't warn about its usage when using a deployment target of iOS 16, without a proper #if available verification. In Xcode Version 16.2 (16C5032a), using swift code, TipUIPopoverViewController can be used without if #available(iOS 17, *) without even trigger a warning or compiler error. This is the snippet we're using in a UIViewController, and it compiles without a warning. @objc private func myMethod() { if presentedViewController is TipUIPopoverViewController { // do something } } Of course this triggers a runtime error, specifically, a EXC_BAD_ACCESS. I was expecting that the same way Xcode warns us when we're using Tips and Tips.Status with iOS 16, this would also trigger a compilation error.
2
0
366
Jan ’25
Bidirectional Text Rendering Issue in Swift UILabel for Arabic
I'm encountering an issue displaying a large HTML string (over 11470 characters) in a UILabel. Specifically, the Arabic text within the string is rendering left-to-right instead of the correct right-to-left direction. I've provided a truncated version of the HTML string and the relevant code snippet below. I've tried setting the UILabel's text alignment to right, but this didn't resolve the issue. Could you please advise on how to resolve this bidirectional text rendering problem? The results of the correct and incorrect approaches are shown in the image below. Here's the relevant Swift code: let labelView: UILabel = { let label = UILabel() label.textAlignment = .right label.translatesAutoresizingMaskIntoConstraints = false label.numberOfLines = 0 label.semanticContentAttribute = .forceRightToLeft label.backgroundColor = .white label.lineBreakMode = .byWordWrapping return label }() //Important!! //It must exceed 11470 characters. let htmlString = """ <p style=\"text-align: center;\"><strong>İSTİÂZE</strong></p> <p>Nahl sûresindeki:</p> <p dir="rtl" lang="ar"> فَاِذَا قَرَاْتَ الْقُرْاٰنَ فَاسْتَعِذْ بِاللّٰهِ مِنَ الشَّيْطَانِ الرَّج۪يمِ </p> <p><strong>“</strong><strong>Kur’an okuyacağın zaman kovulmuş şeytandan hemen Allah’a sığın!</strong><strong>”</strong> (Nahl 16/98) emri gereğince Kur’ân-ı Kerîm okumaya başlarken:</p> <p dir="rtl" lang="ar">اَعُوذُ بِاللّٰهِ مِنَ الشَّيْطَانِ الرَّج۪يمِ</p> <p><em>“Kovulmuş şeytandan Allah’a sığınırım” </em>deriz. Bu sözü söylemeye “istiâze<em>” denilir. “Eûzü”</em>, sığınırım, emân dilerim, yardım taleb ederim, gibi anlamlara gelir. It must exceed 11470 characters.</p> “”” if let data = htmlString.data(using: .utf8) { let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [ .documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue ] do { let attributedString = try NSAttributedString(data: data, options: options, documentAttributes: nil) labelView.attributedText = attributedString } catch { print("HTML string işlenirken hata oluştu: \(error)") } } I'm using iOS 18.2 and Swift 6. Any suggestions on how to correct the bidirectional text rendering?
0
0
325
Jan ’25
Apple TV HDMI Connected device turn off detection problem via HDMI
Hello, we have HLS Stream app on Apple TV. Our streams are DRM protected. We have problem with streams when source device is turned off. For example, user start to watch our HLS DRM Protected content. After some time, user turns off device (it can be Monitor or TV via connected HDMI). Our app does not understand HDMI Source device turned off. Is there any way to understand HDMI connected device is turned off on Swift?
0
0
376
Jan ’25
SwiftUIKit Got double back button and blank screen
I tried to update my ios from 17.2 to 18.1 on my iphone 14 pro. I use this device for testing my apps. when i go to my sdk, i got double back button and when i clicked the back button it will go to blank screen here is the ss double back button got blank screen its never happened on ios 17 and below i use coordinator and UINavigationController anyone have solutions?
1
0
268
Jan ’25
Why doesn’t getAPI() show up in autocomplete despite having a default implementation in a protocol extension?
I’m working on a project in Xcode 16.2 and encountered an issue where getAPI() with a default implementation in a protocol extension doesn’t show up in autocomplete. Here’s a simplified version of the code: import Foundation public protocol Repository { func getAPI(from url: String?) } extension Repository { public func getAPI(from url: String? = "https://...") { getAPI(from: url) } } final class _Repository: Repository { func getAPI(from url: String?) { // Task... } } let repo: Repository = _Repository() repo.getAPI( // Autocomplete doesn't suggest getAPI() I’ve tried the following without success: • Clean build folder • Restart Xcode • Reindexing Is there something wrong with the code, or is this a known issue with Xcode 16.2? I’d appreciate any insights or suggestions.
3
0
502
Jan ’25
Converted Model Preview Issues in Xcode
Hello! I have a TrackNet model that I have converted to CoreML (.mlpackage) using coremltools, and the conversion process appears to go smoothly as I get the .mlpackage file I am looking for with the weights and model.mlmodel file in the folder. However, when I drag it into Xcode, it just shows up as 4 script tags (as pictured) instead of the model "interface" that is typically expected. I initially was concerned that my model was not compatible with CoreML, but upon logging the conversions, everything seems to be converted properly. I have some code that may be relevant in debugging this issue: How I use the model: model = BallTrackerNet() # this is the model architecture which will be referenced later device = self.device # cpu model.load_state_dict(torch.load("models/balltrackerbest.pt", map_location=device)) # balltrackerbest is the weights model = model.to(device) model.eval() Here is the BallTrackerNet() model itself: import torch.nn as nn import torch class ConvBlock(nn.Module): def __init__(self, in_channels, out_channels, kernel_size=3, pad=1, stride=1, bias=True): super().__init__() self.block = nn.Sequential( nn.Conv2d(in_channels, out_channels, kernel_size, stride=stride, padding=pad, bias=bias), nn.ReLU(), nn.BatchNorm2d(out_channels) ) def forward(self, x): return self.block(x) class BallTrackerNet(nn.Module): def __init__(self, out_channels=256): super().__init__() self.out_channels = out_channels self.conv1 = ConvBlock(in_channels=9, out_channels=64) self.conv2 = ConvBlock(in_channels=64, out_channels=64) self.pool1 = nn.MaxPool2d(kernel_size=2, stride=2) self.conv3 = ConvBlock(in_channels=64, out_channels=128) self.conv4 = ConvBlock(in_channels=128, out_channels=128) self.pool2 = nn.MaxPool2d(kernel_size=2, stride=2) self.conv5 = ConvBlock(in_channels=128, out_channels=256) self.conv6 = ConvBlock(in_channels=256, out_channels=256) self.conv7 = ConvBlock(in_channels=256, out_channels=256) self.pool3 = nn.MaxPool2d(kernel_size=2, stride=2) self.conv8 = ConvBlock(in_channels=256, out_channels=512) self.conv9 = ConvBlock(in_channels=512, out_channels=512) self.conv10 = ConvBlock(in_channels=512, out_channels=512) self.ups1 = nn.Upsample(scale_factor=2) self.conv11 = ConvBlock(in_channels=512, out_channels=256) self.conv12 = ConvBlock(in_channels=256, out_channels=256) self.conv13 = ConvBlock(in_channels=256, out_channels=256) self.ups2 = nn.Upsample(scale_factor=2) self.conv14 = ConvBlock(in_channels=256, out_channels=128) self.conv15 = ConvBlock(in_channels=128, out_channels=128) self.ups3 = nn.Upsample(scale_factor=2) self.conv16 = ConvBlock(in_channels=128, out_channels=64) self.conv17 = ConvBlock(in_channels=64, out_channels=64) self.conv18 = ConvBlock(in_channels=64, out_channels=self.out_channels) self.softmax = nn.Softmax(dim=1) self._init_weights() def forward(self, x, testing=False): batch_size = x.size(0) x = self.conv1(x) x = self.conv2(x) x = self.pool1(x) x = self.conv3(x) x = self.conv4(x) x = self.pool2(x) x = self.conv5(x) x = self.conv6(x) x = self.conv7(x) x = self.pool3(x) x = self.conv8(x) x = self.conv9(x) x = self.conv10(x) x = self.ups1(x) x = self.conv11(x) x = self.conv12(x) x = self.conv13(x) x = self.ups2(x) x = self.conv14(x) x = self.conv15(x) x = self.ups3(x) x = self.conv16(x) x = self.conv17(x) x = self.conv18(x) # x = self.softmax(x) out = x.reshape(batch_size, self.out_channels, -1) if testing: out = self.softmax(out) return out def _init_weights(self): for module in self.modules(): if isinstance(module, nn.Conv2d): nn.init.uniform_(module.weight, -0.05, 0.05) if module.bias is not None: nn.init.constant_(module.bias, 0) elif isinstance(module, nn.BatchNorm2d): nn.init.constant_(module.weight, 1) nn.init.constant_(module.bias, 0) Here is also the meta data of my model: [ { "metadataOutputVersion" : "3.0", "storagePrecision" : "Float16", "outputSchema" : [ { "hasShapeFlexibility" : "0", "isOptional" : "0", "dataType" : "Float32", "formattedType" : "MultiArray (Float32 1 × 256 × 230400)", "shortDescription" : "", "shape" : "[1, 256, 230400]", "name" : "var_462", "type" : "MultiArray" } ], "modelParameters" : [ ], "specificationVersion" : 6, "mlProgramOperationTypeHistogram" : { "Cast" : 2, "Conv" : 18, "Relu" : 18, "BatchNorm" : 18, "Reshape" : 1, "UpsampleNearestNeighbor" : 3, "MaxPool" : 3 }, "computePrecision" : "Mixed (Float16, Float32, Int32)", "isUpdatable" : "0", "availability" : { "macOS" : "12.0", "tvOS" : "15.0", "visionOS" : "1.0", "watchOS" : "8.0", "iOS" : "15.0", "macCatalyst" : "15.0" }, "modelType" : { "name" : "MLModelType_mlProgram" }, "userDefinedMetadata" : { "com.github.apple.coremltools.source_dialect" : "TorchScript", "com.github.apple.coremltools.source" : "torch==2.5.1", "com.github.apple.coremltools.version" : "8.1" }, "inputSchema" : [ { "hasShapeFlexibility" : "0", "isOptional" : "0", "dataType" : "Float32", "formattedType" : "MultiArray (Float32 1 × 9 × 360 × 640)", "shortDescription" : "", "shape" : "[1, 9, 360, 640]", "name" : "input_frames", "type" : "MultiArray" } ], "generatedClassName" : "BallTracker", "method" : "predict" } ] I have been struggling with this conversion for almost 2 weeks now so any help, ideas or pointers would be greatly appreciated! Let me know if any other information would be helpful to see as well. Thanks! Michael
1
0
612
Jan ’25
Phone app and CallDirectory
Prior to iOS18, the incoming/outgoing call history display in the Phone app matched the CallDirectory content, but starting with iOS18, changing the information tied to the same number results in the incoming/outgoing call history not matching the CallDirectory content, as it remains unchanged before the change. Is this a strongly intended change? If not, we would like to have it reverted back to the way it worked before iOS18. Befor iOS18 Register the target phone number and name1 to CallRirectory Incoming call using the target phone number The target phone number and name1 is recorded as an incoming call history Register the target phone number and name2 to CallRirectory Incoming call using the target phone number again The target phone number and name2 is recorded as an incoming call history Also 1st incoming call history’s name is changed to name2 After iOS18 Register the target phone number and name1 to CallRirectory Incoming call using the target phone number The target phone number and name1 is recorded as an incoming call history Register the target phone number and name2 to CallRirectory Incoming call using the target phone number again The target phone number and name2 is recorded as an incoming call history But 1st incoming call history’s name is still name1 Why does this difference occur?
2
0
361
Jan ’25
Launch screen more vibrant in iOS18?
Hi! I've detected that in iOS18 launch screen colors differs from the defined ones, that is, if I create a launch screen with a color like #ff0000 (red) and the initial view controller is a view controller with the same color as background, I can see the transition between launch screen and the initial view controller because the launch screen color is different from the other one (dark in this case). I've tested it with several colors: left side is the launch screen and right side is the initial view controller. Both views created with IB using the same colors (it also happens with background images using colors) Is this an intentionall behavior? If so, theres a way to disable it? I need the transition between the launch screen and my initial view controller to be non perceptible... Thanks!
Topic: Design SubTopic: General Tags:
4
1
618
Jan ’25
Why personal music recommendations contain no more than 12 item?
Hi! I get personal recommendations MusicItemCollection using this code: func getRecommendations() async throws -> MusicItemCollection<MusicPersonalRecommendation> { let request = MusicPersonalRecommendationsRequest() let response = try await request.response() let recommendations = response.recommendations return recommendations } However, all recommendations contain no more than 12 MusicItem's, while the Music.app application provides much more for some recommendations, for example, for the You recently listened recommendation, the Music.app application displays 40 items. Each recommendation has an items property that contains a collection of musical items MusicItemCollection<MusicPersonalRecommendation.Item>, the hasNextBatch property for these collections is always false. I expected that for some collections loading of new items would be available. Please tell me if I'm doing something wrong or is this a MusicKit bug? Thank you!
1
0
423
Feb ’25
Not able to save with SwiftData. "The file “default.store” couldn’t be opened."
I get this message when trying to save my Models. CoreData: error: SQLCore dispatchRequest: exception handling request: <NSSQLSaveChangesRequestContext: 0x303034540> , I/O error for database at /var/mobile/Containers/Data/Application/726ECA8C-6C67-4BFE-89E7-AFD8A83CAA5D/Library/Application Support/default.store. SQLite error code:1, 'no such table: ZCALENDARMODEL' with userInfo of { NSFilePath = "/var/mobile/Containers/Data/Application/726ECA8C-6C67-4BFE-89E7-AFD8A83CAA5D/Library/Application Support/default.store"; NSSQLiteErrorDomain = 1; } SwiftData.DefaultStore save failed with error: Error Domain=NSCocoaErrorDomain Code=256 "The file “default.store” couldn’t be opened." UserInfo={NSFilePath=/var/mobile/Containers/Data/Application/726ECA8C-6C67-4BFE-89E7-AFD8A83CAA5D/Library/Application Support/default.store, NSSQLiteErrorDomain=1} The App has Recipes and Calendars and the user can select a Recipe for each Calendar day. The recipe should not be referenced, it should be saved by SwiftData along with the Calendar. import SwiftUI import SwiftData enum CalendarSource: String, Codable { case created case imported } @Model class CalendarModel: Identifiable, Codable { var id: UUID = UUID() var name: String var startDate: Date var endDate: Date var recipes: [String: RecipeData] = [:] var thumbnailData: Data? var source: CalendarSource? // Computed Properties var daysBetween: Int { let days = Calendar.current.dateComponents([.day], from: startDate.midnight, to: endDate.midnight).day ?? 0 return days + 1 } var allDates: [Date] { startDate.midnight.allDates(upTo: endDate.midnight) } var thumbnailImage: Image? { if let data = thumbnailData, let uiImage = UIImage(data: data) { return Image(uiImage: uiImage) } else { return nil } } // Initializer init(name: String, startDate: Date, endDate: Date, thumbnailData: Data? = nil, source: CalendarSource? = .created) { self.name = name self.startDate = startDate self.endDate = endDate self.thumbnailData = thumbnailData self.source = source } // Convenience initializer to create a copy of an existing calendar static func copy(from calendar: CalendarModel) -> CalendarModel { let copiedCalendar = CalendarModel( name: calendar.name, startDate: calendar.startDate, endDate: calendar.endDate, thumbnailData: calendar.thumbnailData, source: calendar.source ) // Copy recipes copiedCalendar.recipes = calendar.recipes.mapValues { $0 } return copiedCalendar } // Codable Conformance private enum CodingKeys: String, CodingKey { case id, name, startDate, endDate, recipes, thumbnailData, source } required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) id = try container.decode(UUID.self, forKey: .id) name = try container.decode(String.self, forKey: .name) startDate = try container.decode(Date.self, forKey: .startDate) endDate = try container.decode(Date.self, forKey: .endDate) recipes = try container.decode([String: RecipeData].self, forKey: .recipes) thumbnailData = try container.decodeIfPresent(Data.self, forKey: .thumbnailData) source = try container.decodeIfPresent(CalendarSource.self, forKey: .source) } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(id, forKey: .id) try container.encode(name, forKey: .name) try container.encode(startDate, forKey: .startDate) try container.encode(endDate, forKey: .endDate) try container.encode(recipes, forKey: .recipes) try container.encode(thumbnailData, forKey: .thumbnailData) try container.encode(source, forKey: .source) } } import SwiftUI struct RecipeData: Codable, Identifiable { var id: UUID = UUID() var name: String var ingredients: String var steps: String var thumbnailData: Data? // Computed property to convert thumbnail data to a SwiftUI Image var thumbnailImage: Image? { if let data = thumbnailData, let uiImage = UIImage(data: data) { return Image(uiImage: uiImage) } else { return nil // No image } } init(recipe: RecipeModel) { self.name = recipe.name self.ingredients = recipe.ingredients self.steps = recipe.steps self.thumbnailData = recipe.thumbnailData } } import SwiftUI import SwiftData @Model class RecipeModel: Identifiable, Codable { var id: UUID = UUID() var name: String var ingredients: String var steps: String var thumbnailData: Data? // Store the image data for the thumbnail static let fallbackSymbols = ["book.pages.fill", "carrot.fill", "fork.knife", "stove.fill"] // Computed property to convert thumbnail data to a SwiftUI Image var thumbnailImage: Image? { if let data = thumbnailData, let uiImage = UIImage(data: data) { return Image(uiImage: uiImage) } else { return nil // No image } } // MARK: - Initializer init(name: String, ingredients: String = "", steps: String = "", thumbnailData: Data? = nil) { self.name = name self.ingredients = ingredients self.steps = steps self.thumbnailData = thumbnailData } // MARK: - Copy Function func copy() -> RecipeModel { RecipeModel( name: self.name, ingredients: self.ingredients, steps: self.steps, thumbnailData: self.thumbnailData ) } // MARK: - Codable Conformance private enum CodingKeys: String, CodingKey { case id, name, ingredients, steps, thumbnailData } required init(from decoder: Decoder) throws { ... } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(id, forKey: .id) try container.encode(name, forKey: .name) try container.encode(ingredients, forKey: .ingredients) try container.encode(steps, forKey: .steps) try container.encode(thumbnailData, forKey: .thumbnailData) } }
1
0
858
Jan ’25
[Xcode:BuildSettings] Keep some warnings as warnings while the rest as errors
We have a big iOS project and we are using .xcconfig files to define our compiler options and build settings. We have our SWIFT_TREAT_WARNINGS_AS_ERRORS set to YES so that all Swift related warnings will be reported as errors. Now, we are trying to migrate to Xcode 16.1 and set 'targeted' in the 'Strict Concurrency Checking' flag. This produces some errors that are related to Swift's concurrency checks. We are now planning to have an approach where we still want to keep SWIFT_TREAT_WARNINGS_AS_ERRORS as is but we want all concurrency related warnings to be still treated as warnings while the rest will get reported as errors. We found this new compiler option - https://forums.swift.org/t/warnings-as-errors-exceptions/72925. It looks like the one we want but I think it is still not out yet and we need to wait until Swift 6.1 (correct me if im wrong). Or is there any other way to do what we want to achieve?
0
0
319
Jan ’25
SceneView selective draw since concurrency
I have used SceneKit for several years but recently have a problem where a scene with fewer than 50 nodes is partially drawn, i.e., some nodes are, some aren't, and greater than 50 nodes are always draw correctly. This seems to have happened since concurrency was introduced. (w.r.t. concurrency, I had been using DispatchQueue successfully before then.) Since all nodes (few or many) are constructed and implemented by the same functions etc. I'm baffled. When I print the node hierarchy all nodes are present whether few or many. SceneView() has [.rendersContinually] option selected. Every node created (few or many) has .opacity = 1.0, .isHidden = false I haven't tried setting-back the compiler version as that is not a long term solution, and I know the same code worked fine then.
8
0
663
Feb ’25
Swift6 race warning
I'm trying to fix some Swift6 warnings, this one seems too strict, I'm not sure how to fix it. The variable path is a String, which should be immutable, it's a local variable and never used again inside of the function, but still Swift6 complains about it being a race condition, passing it to the task What should I do here to fix the warning?
4
0
587
Jan ’25
Ability to retrieve keychain item appears to be lost after restoring an IOS Device
On some production devices our application fails to find the keychain item associated with our application where we store our JWT tokens. We have been unable to reproduce this in house for many months. Today I restored a phone from a backup using the device to device transfer of data as I replaced my personal phone. On that device now when opened each time I am prompted to login again and it appears my token is never saved to the keychain. Upon every successive reopen of the application I see this error in the console. Error fetching keychain item - Error Domain=NSOSStatusErrorDomain Code=-25300 "no matching items found" UserInfo={numberOfErrorsDeep=0, NSDescription=no matching items found} I currently do not see any errors in the console related to the saving of said token. We access this token with the after first unlock security and we do not allow iCloud backup for these tokens. Any help here would be appreciated. I'm not sure what would cause an issue like this. Other applications on my device do not seem to have this issue, so Its likely something we're doing code wise that may be different. Any hints as to what to look for here may be of help. The previous device or any device i have not created from a backup works as intended, including about 95% of our production users.
4
2
429
Jan ’25
Writing an `NWProtocolFramerImplementation` to run on top of `NWProtocolWebSocket`
Hi All, I am trying to write an NWProtocolFramerImplementation that will run after Websockets. I would like to achieve two goals with this Handle the application-layer authentication handshake in-protocol so my external application code can ignore it Automatically send pings periodically so my application can ignore keepalive I am running into trouble because the NWProtocolWebsocket protocol parses websocket metadata into NWMessage's and I don't see how to handle this at the NWProtocolFramerImplementation level Here's what I have (see comments for questions) class CoolProtocol: NWProtocolFramerImplementation { static let label = "Cool" private var tempStatusCode: Int? required init(framer: NWProtocolFramer.Instance) {} static let definition = NWProtocolFramer.Definition(implementation: CoolProtocol.self) func start(framer: NWProtocolFramer.Instance) -> NWProtocolFramer.StartResult { return .willMarkReady } func wakeup(framer: NWProtocolFramer.Instance) { } func stop(framer: NWProtocolFramer.Instance) -> Bool { return true } func cleanup(framer: NWProtocolFramer.Instance) { } func handleOutput(framer: NWProtocolFramer.Instance, message: NWProtocolFramer.Message, messageLength: Int, isComplete: Bool) { // How to write a "Message" onto the next protocol handler. I don't want to just write plain data. // How to tell the websocket protocol framer that it's a ping/pong/text/binary... } func handleInput(framer: NWProtocolFramer.Instance) -> Int { // How to handle getting the input from websockets in a message format? I don't want to just get "Data" I would like to know if that data is // a ping, pong, text, binary, ... } } If I implementing this protocol at the application layer, here's how I would send websocket messages class Client { ... func send(string: String) async throws { guard let data = string.data(using: .utf8) else { return } let metadata = NWProtocolWebSocket.Metadata(opcode: .text) let context = NWConnection.ContentContext( identifier: "textContext", metadata: [metadata] ) self.connection.send( content: data, contentContext: context, isComplete: true, completion: .contentProcessed({ [weak self] error in ... }) ) } } You see at the application layer I have access to this context object and can access NWProtocolMetadata on the input and output side, but in NWProtocolFramer.Instance I only see final func writeOutput(data: Data) which doesn't seem to include context anywhere. Is this possible? If not how would you recommend I handle this? I know I could re-write the entire Websocket protocol framer, but it feels like I shouldn't have to if framers are supposed to be able to stack.
1
0
260
Jan ’25
Unexpected Insertion of U+2004 (Space) When Using UITextView with Pinyin Input on iOS 18
I encountered an issue with UITextView on iOS 18 where, when typing Pinyin, extra Unicode characters such as U+2004 are inserted unexpectedly. This occurs when using a Chinese input method. Steps to Reproduce: 1. Set up a UITextView with a standard delegate implementation. 2. Use a Pinyin input method to type the character “ㄨ”. 3. Observe that after the character “ㄨ” is typed, extra spaces (U+2004) are inserted automatically between the characters. Code Example: class ViewController: UIViewController { @IBOutlet weak var textView: UITextView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } } extension ViewController: UITextViewDelegate { func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { print("shouldChangeTextIn: range \(range)") print("shouldChangeTextIn: replacementText \(text)") return true } func textViewDidChange(_ textView: UITextView) { let currentText = textView.text ?? "" let unicodeValues = currentText.unicodeScalars.map { String(format: "U+%04X", $0.value) }.joined(separator: " ") print("textViewDidChange: textView.text: \(currentText)") print("textViewDidChange: Unicode Scalars: \(unicodeValues)") } } Output: shouldChangeTextIn: range {0, 0} shouldChangeTextIn: replacementText ㄨ textViewDidChange: textView.text: ㄨ textViewDidChange: Unicode Scalars: U+3128 ------------------------ shouldChangeTextIn: range {1, 0} shouldChangeTextIn: replacementText ㄨ textViewDidChange: textView.text: ㄨ ㄨ textViewDidChange: Unicode Scalars: U+3128 U+2004 U+3128 ------------------------ shouldChangeTextIn: range {3, 0} shouldChangeTextIn: replacementText ㄨ textViewDidChange: textView.text: ㄨ ㄨ ㄨ textViewDidChange: Unicode Scalars: U+3128 U+2004 U+3128 U+2004 U+3128 This issue may affect text processing, especially in cases where precise text manipulation is required, such as calculating ranges in shouldChangeTextIn.
5
0
975
Jan ’25