public func getVideoThumbnailImage(url: URL) -> Image {
let urlAsset = AVURLAsset(url: url, options: nil)
let assetImageGenerator = AVAssetImageGenerator(asset: urlAsset)
assetImageGenerator.appliesPreferredTrackTransform = true
assetImageGenerator.apertureMode = .encodedPixels
let cmTime = CMTime(seconds: 1, preferredTimescale: 60)
var thumbnailCGImage: CGImage?
var errorOccurred = false
let semaphore = DispatchSemaphore(value: 0)
assetImageGenerator.generateCGImageAsynchronously(for: cmTime) { generatedImage, timeGenerated, error in
if error == nil {
if let cgVideoImage = generatedImage {
thumbnailCGImage = cgVideoImage
} else {
errorOccurred = true
}
} else {
errorOccurred = true
}
semaphore.signal()
return
}
_ = semaphore.wait(timeout: .now() + 30)
if errorOccurred {
return Image("ImageUnavailable")
}
if let thumbnailImage = thumbnailCGImage {
let uiImage = UIImage(cgImage: thumbnailImage)
return Image(uiImage: uiImage)
}
return Image("ImageUnavailable")
}
I am using Xcode 16 beta 2 for iOS 18 with SwiftUI.
My code above works instantly and correctly; however, Xcode produces the purple warning: "Thread running at User-interactive quality-of-service class waiting on a lower QoS thread running at Default quality-of-service class. Investigate ways to avoid priority inversions"
How can I change the code to avoid the purple warning?
Explore the various UI frameworks available for building app interfaces. Discuss the use cases for different frameworks, share best practices, and get help with specific framework-related questions.
Post
Replies
Boosts
Views
Activity
DESCRIPTION OF PROBLEM
I have changed my app to the @Observable-Macro.
When using an iPhone (on simulator and on real device) the navigation from a player to the player detail view and back breaks. In the attached video on my GitHub you can see me tapping on both players in the team, but the navigation ist not showing the detail view.
What is the reason? Is my usage/understanding of @Observable wrong? Is it wrong to have the selectedPlayer within the PlayerController which is @Observable? And why does it sometimes work and sometimes not?
The project can be found here: GitHub Project
STEPS TO REPRODUCE
Start the App, add one or two demo teams, tap on a team and add two or more demo players.
tap a player and then go back, tap the player again and back again. After a while (number of taps is always different), the navigation breaks. See my video attached.
PLATFORM AND VERSION
iOS
Development environment: Xcode 15.4, macOS 14.5 (23F79)
Run-time configuration: iOS 17.5,
A crash when Use UITextfield to display special characters "美҈̛̍̐̃͒̑́̌̆̾̒̿̒̚̚҈҉̵̶̸̷̷҇̒́̎͐͊̎̑̆́̓̽͂̊͋̑͛͑̈́̉̄̿́̏̽̎̓̋̓́̀̿͒͗͐̇҇͌̏͛͐̈́̑̀̏̏̋̏͑̊͋̈́̉̃̀̉͌̾̍͐͊̃́̉̍̈̎̒̊̉̚̕̚͠͝͠ 】". the system is iOS 16.3.1 and iOS 17.5.1
0
CoreFoundation
___exceptionPreprocess + 164
1
libobjc.A.dylib
_objc_exception_throw + 60
2
Foundation
_blockForLocation
3
UIFoundation
-[NSTextLineFragment _defaultRenderingAttributesAtCharacterIndex:effectiveRange:] + 104
4
UIFoundation
___53-[NSTextLineFragment initWithAttributedString:range:]_block_invoke + 72
5
CoreText
TLine::DrawGlyphsWithAttributeOverrides(CGContext*, __CFDictionary const* ( block_pointer)(long, CFRange*), void ( block_pointer)(CTLineDecorationType, void const*, bool, double, double, double, int, CGPoint, CFRange)) const + 424
6
UIFoundation
__NSCoreTypesetterRenderLine + 368
7
UIFoundation
-[NSTextLineFragment drawAtPoint:graphicsContext:] + 164
8
UIFoundation
-[NSTextLineFragment drawAtPoint:inContext:] + 88
9
UIFoundation
-[NSTextLayoutFragment drawAtPoint:inContext:] + 244
10
UIKitCore
__UITextCanvasDrawWithFadedEdgesInContext + 256
11
UIKitCore
-[_UITextLayoutFragmentView drawRect:] + 228
12
UIKitCore
-[UIView(CALayerDelegate) drawLayer:inContext:] + 508
13
QuartzCore
CABackingStoreUpdate + 252
14
QuartzCore
___ZN2CA5Layer8display_Ev_block_invoke + 64
15
QuartzCore
-[CALayer _display] + 1636
16
QuartzCore
CA::Layer::layout_and_display_if_needed(CA::Transaction*) + 416
17
QuartzCore
CA::Context::commit_transaction(CA::Transaction*, double, double*) + 464
18
QuartzCore
CA::Transaction::commit() + 648
19
QuartzCore
CA::Transaction::flush_as_runloop_observer(bool) + 88
20
UIKitCore
__UIApplicationFlushCATransaction + 52
21
UIKitCore
__UIUpdateSequenceRun + 84
22
UIKitCore
_schedulerStepScheduledMainSection + 172
23
UIKitCore
_runloopSourceCallback + 92
24
CoreFoundation
_CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION + 28
25
CoreFoundation
___CFRunLoopDoSource0 + 176
26
CoreFoundation
___CFRunLoopDoSources0 + 244
27
CoreFoundation
___CFRunLoopRun + 828
28
CoreFoundation
_CFRunLoopRunSpecific + 608
29
GraphicsServices
_GSEventRunModal + 164
30
UIKitCore
-[UIApplication _run] + 888
31
UIKitCore
_UIApplicationMain + 340
32
UIKitCore
_keypath_get_selector_hoverStyle + 11024
Dear Apple Support Team,
I am currently developing a control in my app that uses UIDatePicker for time input. To ensure that the time display format is consistently in 24-hour notation regardless of the region, I have set the locale of UIDatePicker to ‘systemLocale’.
However, while this worked as expected up to iPadOS15, displaying the time in 24-hour format, it has switched to a 12-hour format from iPadOS16 onwards. I am wondering if there have been any changes in the behavior of UIDatePicker’s locale between the updates from iPadOS15 to iPadOS16?
Additionally, I would like to know if there are any workarounds to this issue that do not involve modifying the program. In other words, is there a way to revert back to the 24-hour format without changing the code?
Any information you could provide on this issue would be greatly appreciated. Thank you for your assistance.
I have a live activity, that works fine when the Lock Screen showing, but as soon as it "sleeps" dims down for always on display, everything in the widget disappears and an Activity Indicator(spinner), displays in its place, but non-animating.
I can "import" my shared iCloud Shortcut that contains setup questions for the user in a clickable link in a mail message, but when I try to do that using the same clickable link in a SwiftUI iOS app, I only get the "add" option, not the "Setup" questions
Is there a way to do this?
I'm looking into developing a Pass that drills down into other screens and would add buttons below a pass.
I'm finding it hard to get any information on these capabilities. Does anyone have any resources that might help.
Essentially, mixing features between different pass types (payment cards, generic passes, etc).
I am making application where I use navigation link to navigate from bottom menu to other views, and there is a problem when I change view a few times because views start stacking and when I set navigationBarBackButtonHidden(false) I can see on left side a lot of back button. This generate big problem because after changing views I got warning Abnormal number of gesture recognizer dependencies: 100. System performance may be affected. Please investigate reducing gesture recognizers and/or their dependencies. And after some more changes everything from screen is pushed down back button. Is there any solution to close previous view from we came?
There is code:
//
// BottomMenu.swift
// SpaceManager
//
// Created by Kuba Kromomołowski on 04/05/2024.
//
import SwiftUI
import Firebase
import FirebaseAuth
struct BottomMenu: View {
@StateObject var logManager = MainViewModel()
@StateObject var mvm = MenuViewModel()
@State var condition1: Bool = true
@State var condition2: Bool = false
@State var condition3: Bool = false
// @StateObject private var cameraViewModel = CameraViewModel()
var body: some View {
HStack{
Group{
//.navigationBarBackButtonHidden(true)
Spacer()
BtnMenu(btnText: "Dodaj",
btnIcon: "plus.app.fill",
destinationView:AnyView(LoggedMainView()),
isActive: condition1
)
Spacer()
BtnMenu(btnText: "Szukaj",
btnIcon: "magnifyingglass",
destinationView:AnyView(SearchView()),
isActive: condition2
)
Spacer()
BtnMenu(btnText: "Profil",
btnIcon: "person.crop.circle.fill",
destinationView:AnyView(ProfileView()),
isActive: condition3
)
Spacer()
}.padding(.bottom, 30)
.font(.system(size: 20))
}
}
}
#Preview {
BottomMenu()
}
//
// BtnMenu.swift
// SpaceManager
//
// Created by Kuba Kromomołowski on 04/05/2024.
//
import SwiftUI
struct BtnMenu: View {
var btnText: String
var btnIcon: String
var destinationView: AnyView
@State var isActive: Bool = true
var body: some View {
NavigationLink{
destinationView
} label: {
ZStack {
Text("\(Image(systemName: btnIcon)) \(btnText)")
}
}.disabled(isActive)
}
}
I am in the process of adding my company's brand font to our SwiftUI app. I am able to implement the font using the provided public APIs so that text styles / dynamic type and the font weight modifier in SwiftUI work correctly.
However we are unable to implement custom font in such a way that text styles / dynamic type, the font weight modifier, and the bold text accessibility setting all work at the same time. Am I missing an implementation detail so that all these features work correctly?
Font Setup
The font files were modified to better support SwiftUI:
The font style name metadata was modified to match the name the .fontWeight(...) modifier expects. This was done with Typelight.
The font weight value (100/200/300) was modified so that the underlying weight value matches the value the .fontWeight(...) modifier expects. See "Using custom fonts with SwiftUI" by Matthew Flint.
The font files were imported via the Info.plist.
Examples
Font Weight Comparison
San Fransisco:
Text("#100")
.font(.largeTitle)
.fontWeight(.ultraLight)
Overpass by Name:
Text("#100")
.font(.custom("Overpass-UltraLight", size: 34, relativeTo: .largeTitle))
Overpass by Weight:
Text("#100")
.fontWeight(.ultraLight)
.font(.custom("Overpass", size: 34, relativeTo: .largeTitle))
Legibility Weight Test
When using the .fontWeight(...) modifier, the custom font does not change weights when the bold text accessibility setting is enabled. Dynamic type size works as expected.
Normal legibility weight:
Bold legibility weight:
Dynamic Type Size:
Use UIFont
Using UIFont to load the custom font files and initializing a Font with the UIFont breaks dynamic type:
Bold type also does not work:
Custom Modifier
Creating a custom modifier allows us to support dynamic type and manually handle bold text. However it creates a conflicting API to SwiftUI's .fontWeight(...) modifier.
struct FontModifier: ViewModifier {
enum UseCase {
case paragraph
case headline
}
enum Weight {
case light
case regular
case heavy
}
@Environment(\.legibilityWeight) var legibilityWeight
var useCase: UseCase
var weight: Weight
init(_ useCase: UseCase, _ weight: Weight) {
self.useCase = useCase
self.weight = weight
}
var resolvedHeadlineWeight: String {
let resolvedLegibilityWeight = legibilityWeight ?? .regular
switch weight {
case .light:
switch resolvedLegibilityWeight {
case .regular:
return "Light"
case .bold:
return "Semibold"
@unknown default:
return "Light"
}
case .regular:
switch resolvedLegibilityWeight {
case .regular:
return "Regular"
case .bold:
return "Bold"
@unknown default:
return "Regular"
}
case .heavy:
switch resolvedLegibilityWeight {
case .regular:
return "Heavy"
case .bold:
return "Black"
@unknown default:
return "Heavy"
}
}
}
var resolvedParagraphWeight: Font.Weight {
switch weight {
case .light:
return .light
case .regular:
return .regular
case .heavy:
return .heavy
}
}
var resolvedFont: Font {
switch useCase {
case .paragraph:
return .system(.largeTitle).weight(resolvedParagraphWeight)
case .headline:
return .custom("Overpass-\(resolvedHeadlineWeight)", size: 34, relativeTo: .largeTitle)
}
}
func body(content: Content) -> some View {
content
.font(resolvedFont)
}
}
GridRow {
Text("Aa")
.modifier(FontModifier(.paragraph, .regular))
Text("Aa")
.modifier(FontModifier(.paragraph, .heavy))
Text("Aa")
.modifier(FontModifier(.headline, .regular))
Text("Aa")
.modifier(FontModifier(.headline, .heavy))
}
Font Environment Value
The font environment value does not contain font weight information when the fontWeight(...) modifier is used.:
struct DumpFontTest: View {
@Environment(\.font) var font
var body: some View {
Text("San Fransisco")
.onAppear {
print("------------")
dump(font)
}
}
}
Hello.
I want to do a fetch when a view loads. In UIKit I would have used viewDidLoad to do this but in SwiftUI we only have onAppear and task. Is that by design, and if so, what is the recommended way to fetch data?
I wrote a little blog post for a workaround describing the issue and the found solution, but I presume there is a better way.
https://www.ludafux.com/post/viewdidload_doppelganger
Best Regards,
Luda
Hello,
I am getting following errors in Xcode console when running my app on the simulator with iPad Pro 13-inch (M4) 17.4:
CoreUI: _Bool CUIValidateIdiomSubtypes(NSInteger, NSUInteger *) passed a device subtype '2752' and idiom '2':pad that are not a matching pair, subtype is not valid with given idiom. Assuming subtype should be 0 instead.
This is the code:
import Foundation
import SwiftUI
struct PrefersTabNavigationEnvironmentKey: EnvironmentKey {
static var defaultValue: Bool = false
}
extension EnvironmentValues {
var prefersTabNavigation: Bool {
get { self[PrefersTabNavigationEnvironmentKey.self] }
set { self[PrefersTabNavigationEnvironmentKey.self] = newValue }
}
}
#if os(iOS)
extension PrefersTabNavigationEnvironmentKey: UITraitBridgedEnvironmentKey {
static func read(from traitCollection: UITraitCollection) -> Bool {
return traitCollection.userInterfaceIdiom == .phone || traitCollection.userInterfaceIdiom == .pad || traitCollection.userInterfaceIdiom == .tv
}
static func write(to mutableTraits: inout UIMutableTraits, value: Bool) {
// do not write
}
}
#endif
I am using this to decide what layout of the app to use – learned this from the Apple sample app Backyards Birds:
if prefersTabNavigation {
AppTabView(selection: $selection)
} else {
NavigationSplitView {
AppSideBar(selection: $selection)
} detail: {
AppDetailColumn(screen: selection)
}
}
Could you please help me find out what is wrong with the code?
How to make some label UI render to the front of 3D objects in the development of vision pro
On the WWDC24 session video 'Enhance your UI animations and transitions', Appls shows these new animation methods for UIKIT:
switch gesture.state {
case .changed:
UIView. animate(.interactiveSpring) {
bead.center = gesture.translation
}
case .ended:
UIView. animate(spring) {
bead.center = endOfBracelet
}
}
As of iOS 18 Beta 2, I get an error for `UIView. animate(.interactiveSpring)`
These new methods are not available yet?
I have an extremely (et cetera ad infinitum) textview that is lagging when typing (presumably) because of the text.
Not sure what textkit is doing under the hood but if I were building it from scratch I wouldn't need to do any calc when the user is typing. I could just would design it so each new line is like's it's own textfield so to speak. But clearly that isn't the case. Any suggestions / can someone at Apple on the textkit team reach out ? (I interviewed with someone from that team before so I know it exists lol)
Hey y'all, im semi new to the coding world and have just come across this error: Failed to produce diagnostic for expression; please submit a bug report (https://swift.org/contributing/#reporting-bugs) ive been building for a little while and can't figure out why. Ive rebuilt and tried everything. Any help would be appreciated!
This is the code:
import SwiftUI
import Combine
struct LoginView: View {
@EnvironmentObject var authManager: AuthenticationManager
@State private var email = ""
@State private var password = ""
@State private var showingAlert = false
@State private var alertMessage = ""
@State private var keyboardHeight: CGFloat = 0
var body: some View {
GeometryReader { geometry in
NavigationView {
ZStack {
LinearGradient(gradient: Gradient(colors: [Color.red, Color.black]), startPoint: .top, endPoint: .bottom)
.edgesIgnoringSafeArea(.all)
VStack {
Image("GottaDraftEmAll")
.resizable()
.scaledToFit()
.frame(width: geometry.size.width * 0.8, height: geometry.size.height * 0.1)
.padding(.top, 25)
Spacer()
Image("pokeball")
.resizable()
.scaledToFit()
.frame(width: geometry.size.width * 0.6, height: geometry.size.width * 0.6)
.padding(.bottom, 20)
VStack(spacing: 15) {
TextField("", text: $email)
.padding()
.background(Color.white.opacity(0.8))
.cornerRadius(10)
.padding(.horizontal, 20)
.foregroundColor(.black)
.overlay(
HStack {
Text(email.isEmpty ? "Email" : "")
.foregroundColor(Color.black.opacity(0.7))
.padding(.leading, 25)
Spacer()
}
)
SecureField("", text: $password)
.padding()
.background(Color.white.opacity(0.8))
.cornerRadius(10)
.padding(.horizontal, 20)
.foregroundColor(.black)
.overlay(
HStack {
Text(password.isEmpty ? "Password" : "")
.foregroundColor(Color.black.opacity(0.7))
.padding(.leading, 25)
Spacer()
}
)
}
.padding(.top, 50)
Button(action: {
authManager.signIn(email: email, password: password) { success, error in
if !success {
alertMessage = error ?? "An unknown error occurred"
showingAlert = true
}
}
}) {
Text("LOGIN")
.font(.headline)
.foregroundColor(.white)
.padding()
.frame(maxWidth: .infinity)
}
.buttonStyle(GlowGradientButtonStyle())
.padding(.horizontal, 20)
.padding(.top, 20)
NavigationLink(destination: SignUpView()) {
Text("Don't have an account? Sign Up")
.foregroundColor(.white)
}
.padding(.top, 10)
Spacer()
}
.padding(.bottom, keyboardHeight)
}
.onAppear {
NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillShowNotification, object: nil, queue: .main) { notification in
if let value = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect {
self.keyboardHeight = value.height
}
}
NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillHideNotification, object: nil, queue: .main) { _ in
self.keyboardHeight = 0
}
}
.onDisappear {
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
}
.alert(isPresented: $showingAlert) {
Alert(title: Text("Login Error"), message: Text(alertMessage), dismissButton: .default(Text("OK")))
}
}
}
}
}
After installation of beta update. The app icons are not loading in home screen even after multiple phone restarts
Problem Description:
I used Swift code to change a folder icon by calling the NSWorkspace.shared.setIcon(_:forFile:options:) method. The specific code is as follows:
NSWorkspace.shared.setIcon(coloredIcon, forFile: folderURL.path, options: [.exclude10_4ElementsIconCreationOption])
I noticed that the folder icon has been correctly changed in the Finder preview window, but the icon displayed on the desktop is still the original one.
Expected Result:
I hope the folder icon on the desktop can also be updated to display the new icon.
Solutions Tried:
I have tried restarting Finder and manually refreshing the icon cache, but the folder icon on the desktop still does not update.
Help Needed:
I would like to know if there is a way to automatically refresh the desktop folder icon cache in Swift code to ensure that the changed icon can be immediately displayed.
Hi,
I was testing my project running on macOS 15 Beta and Xcode 16 Beta and noticed that lists look slightly different. They generally look somewhat smaller, like the font size or spacing is now different.
It's kinda hard to describe so I made screenshots depicting what the list looks like on macOS 14 + Xcode 15 and macOS 15 Beta + Xcode 16 Beta to show what I mean.
Did you experience similar issues?
Hello! I have been working on an app for quite some time now, and one of my views is of a bunch of different articles that my brand has written. The articles can be found on their website, and so as of late, I have just been copying and pasting all of the data from each article into a JSON file in my app; However, as the list of articles grow, I need to fetch the data directly from the website and have it integrated with my code, so every time a new article is published, users dont have to update their app. Is there any way someone could help with this? I've been struggling for a while now. Thanks!
I am trying to replace the navigation tab bar with a custom bottom toolbar when a view enters edit mode. Currently, I am using the following code to achieve this:
content
.toolbar(isEditing ? .hidden : .visible, for: .tabBar)
. toolbar(isEditing ? .visible : .hidden, for: .bottomBar)
However, this results in a janky animation. When the bottom bar appears, it animates in above (in contrast to in place of) the tab bar, then "jumps" back down to the correct offset without animation. I had to workaround this by delaying the appearance of bottom bar by 0.3s. I am already using withAnimation().
Is this a bug or am I using the APIs incorrectly? Is there a more seamless way to achieve this switching effect other than delaying the bottom bar? Thanks!