I have received permission from Apple to access SensorKit data for my app. I have granted all necessary permissions, but no data is being retrieved.
The didCompleteFetch method is being called, but I’m unsure where to find event data like Device Usage and Ambient Light. Additionally, the didFetchResult method is never called.
Could anyone please assist me in resolving this issue? Any guidance or troubleshooting steps would be greatly appreciated.
import SensorKit
class ViewController: UIViewController, SRSensorReaderDelegate {
let store = SRSensorReader(sensor: .deviceUsageReport)
override func viewDidLoad() {
super.viewDidLoad()
requestSensorAuthorization()
}
func requestSensorAuthorization() {
var sensors: Set<SRSensor> = [
.accelerometer,
.deviceUsageReport,
.messagesUsageReport,
.visits,
.keyboardMetrics,
.phoneUsageReport,
.ambientLightSensor
]
if #available(iOS 16.4, *) {
sensors.insert(.mediaEvents)
}
SRSensorReader.requestAuthorization(sensors: sensors) { error in
if let error = error {
print("Authorization failed: \(error.localizedDescription)")
} else {
self.store.startRecording()
self.requestSensorData()
print("Authorization granted for requested sensors.")
}
}
}
func requestSensorData() {
let fromTime = SRAbsoluteTime.fromCFAbsoluteTime(_cf: Date().addingTimeInterval(-60 * 60).timeIntervalSinceReferenceDate)
let toTime = SRAbsoluteTime.fromCFAbsoluteTime(_cf: Date().timeIntervalSinceReferenceDate)
let request = SRFetchRequest()
request.from = fromTime
request.to = toTime
request.device = SRDevice.current
store.fetch(request)
store.delegate = self
}
func sensorReader(_ reader: SRSensorReader, didCompleteFetch fetchRequest: SRFetchRequest) {
print("Fetch request completed: \(fetchRequest.from) to \(fetchRequest.to)")
Task {
do {
let samples = try await reader.fetch(fetchRequest)
print("Samples count: \(samples)")
} catch {
print("Error Fetching Data: \(error.localizedDescription)")
}
}
}
func sensorReader(_ reader: SRSensorReader, fetching fetchRequest: SRFetchRequest, didFetchResult result: SRFetchResult<AnyObject>) -> Bool {
print(result)
return true
}
}
How did we do? We’d love to know your thoughts on this year’s conference. Take the survey here
UIKit
RSS for tagConstruct and manage graphical, event-driven user interfaces for iOS or tvOS apps using UIKit.
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
This is a very strange behavior when pushing vc that I have never seen since I started coding. The pushed ViewController is transparent and only navBarTitle is shown. After the push, you can't control anything unless you go back to the home screen.
STEPS TO REPRODUCE
Long press currency change button below.(currencyWrapper)
Call selectCountry and this bug happens.
SourceCode
let currencyWrapper = UIView()
private func configureCurrencyCard(){
//The strange behavior shows up after long pressing this
currencyWrapper.backgroundColor = .white
currencyWrapper.addTarget(self, action: #selector(changeCurrency))
currencyWrapper.setWidth(currencyChangeIcon.follow(by: 16, x: true))
currencyWrapper.setCenterX(w1/2)
currencyWrapper.setHeight(currencyLabel.follow(by: 12, x: false))
currencyWrapper.roundToCircle(true)
view.addSubview(currencyWrapper)
}
private func selectCountry(country: Country){
let vc = CountryViewController(country: country)
vc.hidesBottomBarWhenPushed = true
navigationController?.pushViewController(vc, animated: true)
}
When testing with iOS 18.4 Beta on iPhones which support Dynamic Island, after doing a Face ID authentication, the amount of time it takes before the AppDelegate method applicationDidBecomeActive() is called takes longer than iPhones that do not support Dynamic Island. The time it takes is about double, 1.2 seconds vs 2.5 seconds on average. This does not occur with versions before 18.4 Beta.
Anyone else seeing this?
Topic:
UI Frameworks
SubTopic:
UIKit
I have a controller that displays a pdf using UIDocumentInteractionController as the presented view.
When users open it up, it shows fine.
User gets the app backgrounded and session timed out.
After timed out, when the app is brought to foreground, I bring our loginVC by removing the old VC used to show the UIDocumentInteractionController.
All the crashes are happening at this point.
I am not able to reproduce it, but our alert systems show we have crashes happening.
The code that shows the pdf is straight forward
documentViewController = UIDocumentInteractionController()
documentViewController?.delegate = self
documentViewController?.url = url
documentViewController?.presentPreview(animated: true)
and we reset it to nil in delegate documentInteractionControllerDidEndPreview
Based on the crash trace, it seems like the crash happens when our login VC replaces it and only when pdf was displayed. The reason of stressing ONLY because when we have other viewcontroller present and they are removed in a similar way, we do not see any issue.
So we always replace first and then add a new one
childViewController.willMove(toParent: nil)
childViewController.viewIfLoaded?.removeFromSuperview()
childViewController.removeFromParent()
addChild(childViewController)
view.addSubview(childViewController.view)
childViewController.view.frame = view.bounds
childViewController.didMove(toParent: self)
Raised a ticket with Apple, but I haven't heard back, and it's been a month. Posting here in case anyone experiences the same and has any solutions. I saw some related posts, and solution was to remove the pdf the moment the app goes to the background, but I am trying to find some alternate solution if possible.
Topic:
UI Frameworks
SubTopic:
UIKit
In my UIKit app, I'm getting this log message in the Xcode console: "What changed the navigation bar bounds size to something unexpected during the animation if it wasn't a showsScopeBar change?"
I could answer this question, but to whom should I be answering? Does this mean that Apple is interested in hearing about situations where this can legitimately occur?
Topic:
UI Frameworks
SubTopic:
UIKit
Hi everyone, i'im having troubles using Annotation on a Map View. I have a a core data model called Location that conforms to NSManagedObject from CoreData and MKAnnotation form MapKit, and i'm trying to add an array of Location to a MKMview instance in a UIViewController class, by doing somethhing like this: mapView.addAnnotation(locations), but xcode compliants with a strange error which says Argument type '[Location]' does not conform to expected type 'MKAnnotation'. it's strange to me because my Location class conforms to MKAnnotation protocol and i implemented the protocol's methods (coordinate, title, subtitle).
Please can anyone help me how to fix this issues. Thank you all
Hey Everyone,
I can't see to ActiveLabel as it says there is no active module. Please help me.
Thanks,
Ben
import UIKit
import ActiveLabel
protocol TweetCellDelegate: AnyObject {
func handleProfileImageTapped(_ cell: TweetCell)
func handleReplyTapped(_ cell: TweetCell)
func handleLikeTapped(_ cell: TweetCell)
}
class TweetCell: UICollectionViewCell {
Hi,
I am getting this crash specific to iOS 18.4. This has happened only on iPad, combined with 18.4. I do not what is causing the crash. I am unable to reproduce the crash. Crash report attached at the bottom of the post.
Thank you.
first.crash
second.crash
We rotate the portrait to landscape then we force rotate to portrait app rotates but the screen seems to be divided into two parts
My sample code
class OrientationHelper {
static func lockOrientation(_ orientation: UIInterfaceOrientationMask) {
if let delegate = UIApplication.shared.delegate as? AppDelegate {
delegate.orientationLock = orientation
}
}
static func lockOrientation(_ orientation: UIInterfaceOrientationMask, andRotateTo rotateOrientation: UIInterfaceOrientation) {
self.lockOrientation(orientation)
DispatchQueue.main.async {
UIDevice.current.setValue(rotateOrientation.rawValue, forKey: "orientation")
UIViewController.attemptRotationToDeviceOrientation()
}
}
}
// Appdelegte
var orientationLock = UIInterfaceOrientationMask.portrait
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
return orientationLock
}
Topic:
UI Frameworks
SubTopic:
UIKit
WKWebView cannot load and display HTTP image resources
Topic:
UI Frameworks
SubTopic:
UIKit
Xcode 16 iOS18 WKWebView里包含http图片时无法显示
Topic:
UI Frameworks
SubTopic:
UIKit
It has been asked several times in the forum, but apple has always maintained that screenshot capture prevention is not supported, how is it that whatsapp and several financial apps are doing it, if screenshot capturing is not possible, its not DRM, is it the adding of a secured text as a layer on to the uiview layer? how have they designed a custom screen if that is the case? Also how is it getting approved by apple! If detection of airplay is possible and can be suppressed, why not screenshot?
Hello,
I just noticed weird unexpected behaviour.
It seems when you present UIAlertController or custom VC as partially screen covering formsheet, ALL the views underneath get 0.8 alpha tint (ios 15 and 18)
Is there any way to disable this behaviour?
So far it only breaks minor custom "star" view but I imagine arbitrarily adding 0.8 alpha to EVERYTHING can really mess up some layouts/designs.
Regards,
Martynas Stanaitis
Topic:
UI Frameworks
SubTopic:
UIKit
Hello team i notice that we have a problem in our app that every time the user opens a Textfield the app freezes when the keyboard appears, this behavior was tracked down and it's a UI breaking design on a UIView
[this view it's expandable and is original size is 80]
[when it gets expanded 206.33]
this is the view code I change the colors to easy check the other's views created inside
private lazy var sharedUIPlaybackView: UIView = {
let containerView = UIView().withAutoLayout()
let propertySearchCriteria = PropertySearchCriteriaBuilder(hotelSearchParameters: viewModel.hotelSearchParameters).criteria
var swiftUIView: SwiftUIView<LodgingPlaybackWrapper>! = nil
swiftUIView = SwiftUIView(
LodgingPlaybackWrapper(propertySearchCriteria: propertySearchCriteria,
playbackUpdateNotificationSender: playbackUpdateNotificationSender,
componentHandler: { [weak self] componentId in
self?.componentReady(componentId)
}),
viewDidLayoutSubviewsCallback: { [weak self] in
let extraPadding = self?.playbackViewExtraPadding ?? Spacing.spacing8x
let newHeight = swiftUIView.frame.size.height + extraPadding
// if newHeight != self?.sharedUIPlaybackViewHeightConstraint?.constant {
// self?.sharedUIPlaybackViewHeightConstraint?.constant = 206.33
// }else {
// self?.sharedUIPlaybackViewHeightConstraint?.constant = 80
// }
}
).withAutoLayout().withAccessibilityIdentifier("test")
// sharedUIPlaybackViewHeightConstraint = containerView.heightAnchor.constraint(equalToConstant: 0)
// sharedUIPlaybackViewHeightConstraint?.isActive = true
containerView.backgroundColor = .blue
swiftUIView.backgroundColor = .red
containerView.addSubview(swiftUIView)
containerView.addConstraints([
swiftUIView.topAnchor.constraint(equalTo: containerView.topAnchor, constant: playbackViewTopConstant),
swiftUIView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: Spacing.spacing4x),
swiftUIView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: -Spacing.spacing4x),
swiftUIView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor, constant: -Spacing.spacing3x),
swiftUIView.heightAnchor.constraint(equalToConstant: 206.33)
])
return containerView
}()
old devs created this function viewDidLayoutSubviewsCallback to connect user interaction on the wrapper and used on UIKit.
this is the part where the math on the function gets weird and messed up the code by crashing the view
viewDidLayoutSubviewsCallback: { [weak self] in
let extraPadding = self?.playbackViewExtraPadding ?? Spacing.spacing8x
let newHeight = swiftUIView.frame.size.height + extraPadding
if newHeight != self?.sharedUIPlaybackViewHeightConstraint?.constant {
self?.sharedUIPlaybackViewHeightConstraint?.constant = newHeight
}
}
).withAutoLayout().withAccessibilityIdentifier("test")
sharedUIPlaybackViewHeightConstraint = containerView.heightAnchor.constraint(equalToConstant: 0)
sharedUIPlaybackViewHeightConstraint?.isActive = true
I commented this math because is crashing the app and instead of giving a dynamical height I placed as a constant constraint as default height this is how I solved the problem of the UI, but I still need to update the view each time the user clicks and gets call by the method viewDidLayoutSubviewsCallback
what can I do?
I tried to add like a conditional on the method
if newHeight == 80 {
containerView.addConstraints([
swiftUIView.heightAnchor.constraint(equalToConstant: 80.0)
])
containerView.layoutIfNeeded()
}
else {
containerView.addConstraints([
swiftUIView.heightAnchor.constraint(equalToConstant: 206.33)
])
containerView.layoutIfNeeded()
}
like this but it didn't work
[this is how it looks with the constant value of 206.33]
[when it gets open looks good]
app crashing in iPad Only and not getting help from logs
Exception Type: EXC_BAD_ACCESS (SIGSEGV)
Exception Subtype: KERN_PROTECTION_FAILURE at 0x000000016d667fd0
Exception Codes: 0x0000000000000002, 0x000000016d667fd0
VM Region Info: 0x16d667fd0 is in 0x16d664000-0x16d668000; bytes after start: 16336 bytes before end: 47
REGION TYPE START - END [ VSIZE] PRT/MAX SHRMOD REGION DETAIL
MALLOC_SMALL 132c00000-133000000 [ 4096K] rw-/rwx SM=PRV
GAP OF 0x3a664000 BYTES
---> STACK GUARD 16d664000-16d668000 [ 16K] ---/rwx SM=NUL stack guard for thread 0
Stack 16d668000-16d764000 [ 1008K] rw-/rwx SM=SHM thread 0
Termination Reason: SIGNAL 11 Segmentation fault: 11
Terminating Process: exc handler [10927]
Triggered by Thread: 0
Thread 0 name: Dispatch queue: com.apple.main-thread
Thread 0 Crashed:
0 UIKitCore 0x186fae04c __66-[UITraitCollection _traitCollectionByModifyingTraitsCopyOnWrite:]_block_invoke_2 + 4
1 UIKitCore 0x186faefdc __54-[UITraitCollection traitCollectionByModifyingTraits:]_block_invoke + 36
2 UIKitCore 0x186fabfc8 -[UITraitCollection _traitCollectionByModifyingTraitsCopyOnWrite:] + 252
3 UIKitCore 0x187109b08 -[UITraitCollection traitCollectionByModifyingTraits:] + 120
4 UIKitCore 0x1871c013c -[UIScreen _defaultTraitCollectionForInterfaceOrientation:inBounds:] + 224
5 UIKitCore 0x1871bff8c -[UIApplication _isOrientationVerticallyCompact:] + 48
6 UIKitCore 0x1871bcd28 -[UIApplication _isStatusBarHiddenForOrientation:] + 24
7 UIKitCore 0x186fe0d10 +[UIWindow(StatusBarManager) _prefersStatusBarHiddenInWindow:targetOrientation:animationProvider:] + 260
8 UIKitCore 0x186fe310c +[UIWindow(StatusBarManager) _prefersStatusBarHiddenInWindow:animationProvider:] + 72
9 UIKitCore 0x186fe2e00 -[UIApplication _isStatusBarEffectivelyHiddenForContentOverlayInsetsForWindow:] + 132
10 UIKitCore 0x186fe0a9c -[UIWindow _sceneSafeAreaInsetsIncludingStatusBar:] + 184
11 UIKitCore 0x187037628 -[UIWindow _normalizedSafeAreaInsets] + 64
12 UIKitCore 0x1870375a0 -[UIWindow safeAreaInsets] + 76
13 UIKitCore 0x186fa6c70 -[UIView _updateSafeAreaInsets] + 68
14 UIKitCore 0x188529824 -[UIView _recursiveEagerlyUpdateSafeAreaInsetsUntilViewController] + 176
I set the titleView of a view controller to a UISlider like so in viewDidLoad:
UISlider *slider = [UISlider new];
self.navigationItem.titleView = slider;
The desired outcome is that the slider takes the full width of the title view. This is working fine when the view is loaded in the wider landscape mode. The slider adjust its size as expected when rotating to portrait mode.
However, when the view is loaded in the narrower portrait mode and then the device is rotated to landscape, the slider does not grow in width to make use of the newly available size.
Why is that so and how can it get the desired outcome as described?
After viewDidLoad:
After rotating:
Hello. Recently, our app has been experiencing crashes with the message 'Attempting to attach window to an invalidated scene' when creating a UIWindow.
Our code stores the UIWindowScene provided in the scene(:willConnectTo:options:) function in a global variable and does not change the set scene until the scene(:willConnectTo:options:) function is called again. Additionally, we do not perform any actions related to the disconnect event.
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
guard let windowScene = (scene as? UIWindowScene) else { return }
hudManager.setup(windowScene: windowScene)
// ...
}
func sceneDidDisconnect(_ scene: UIScene) {
// do nothing
}
In all crash logs, the activationState of the WindowScene is "unattached", so I initially thought that creating a UIWindow with a scene in the 'unattached' state should be avoided.
However, in the scene(_:willConnectTo:options:) function, the scene's state is also 'unattached', yet the UIWindow is created successfully here, which makes me think that deciding whether to create a window based on the activationState is incorrect.
I did find that trying to create a UIWindow with a scene after it has been disconnected causes a crash.
func sceneDidDisconnect(_ scene: UIScene) {
// Crash occur here and scene's state is `unattached`
let window = UIWindow(windowScene: scene as! UIWindowScene)
}
If the activationState alone cannot be used to determine the validity of a scene, is there another way to check the validity of a Scene? Thank you
Hello everyone,
I've run into a peculiar behavior with UINavigationController's setViewControllers on iOS 18.2 (I guess it might be reproducible on older versions) when reordering view controllers, and I wonder if anyone can shed some light on this issue.
Initial State: The navigation stack is [A - B - C].
Without Animation: Setting [A - C - B] updates the stack to: A - C - B as expected.
With Animation: Using the same command with animation changes the stack to [A - B], oddly omitting C.
Has anyone else noticed similar behavior or knows why animations might disrupt the stack's update this way? I'd appreciate any insights or suggestions.
Thanks, Dmytro
I have a struct that holds an instance of UINavigationController:
struct NavigationController {
static let shared = UINavigationController()
}
I use NavigationController.shared to push and pop ViewControllers around the app, rather than using the ViewController's .navigationController property.
The issue I'm having is that when I pop I get new instances of my previous ViewController, this is my hierarchy:
(0) UIWindow
|
---- (1) NavigationController (is set as the UIWindow.rootViewController)
|
---- (2) UITabBarController (is set with NavigationController.shared.setViewControllers)
|
---- (3) ViewController (HomeVC) (is the first tab of the UITabController)
|
---- (4) ViewController (ScanVC) (is pushed into the stack by NavigationController.shared.pushViewController)
---- (5) ViewController (NotificationsVC)
---- (6) ViewController (SettingsVC)
I put a print statement in my HomeVC in the viewDidLoad method
My understanding is that the viewDidLoad should only be called once in the lifecycle of a ViewController
When I go back to the HomeVC from the ScanVC then the print always gets triggered which means I have a new instance of the HomeVC
This is the print statement I created inside the viewDidLoad method:
print("\(#function) View Did Load, instance: \(self)")
Here's the output from going back and forth from the HomeVC to ScanVC:
viewDidLoad() View Did Load, instance: <HomeVC: 0x118db0000>
viewDidLoad() View Did Load, instance: <HomeVC: 0x118db3100>
viewDidLoad() View Did Load, instance: <HomeVC: 0x118db0700>
Any one has any suggestions on how to fix this? Because ideally going back to the HomeVC should not instantiate a new ViewController.
I tested this on a small test project and viewDidLoad would only be triggered once when the ViewController was instantiated.
I'm building an app using UITabbarController with 2 tabs: screen A and B. When standing on tab B and I taps on tab A, the order in which the events are triggered will be:
For iOS < 18:
viewWillDisappear() of screen B
tabBarController(_:didSelect:) of UITabbarController
For iOS >= 18:
tabBarController(_:didSelect:) of UITabbarController
viewWillDisappear() of screen B
So my question is this an issue or a new update from Apple on iOS 18.*?