SwiftUI run-time issue when using an environment object - xcode

I've faced this issue on one of my old projects and I'm sure that there were no runtime issues back then: (current Xcode: 14.1)
The Style is global:
#main
struct TestingApp: App {
var body: some Scene {
WindowGroup {
TestView().environmentObject(Style()) // <- Here
}
}
}
Each page may has access to the style through the EnvironmentObject:
struct TestView: View {
#EnvironmentObject private var style: Style
public var body: some View {
Text("Hello World")
.padding(style.size.inputPadding) // <- Run-time issue on this line
}
}
And the Style itself declared like this:
class Style: ObservableObject {
#Published var size = Size()
}
struct Size {
#ScaledMetric(relativeTo: .body) var inputPadding: CGFloat = 8
}
I'm getting this run-time issue:
Accessing Environment<CGFloat>'s value outside of being installed on a View. This will always read the default value and will not update.
and
Accessing Environment<DynamicTypeSize>'s value outside of being installed on a View. This will always read the default value and will not update.
Can someone explain what is happening and why this is considered as ACCESSING value OUTSIDE of being installed on a View ?

They key part of the issue is where the wrapper is "installed"
#ScaledMetric
Doesn’t work in a regular struct because it conforms to DynamicProperty
https://developer.apple.com/documentation/swiftui/scaledmetric
DynamicProperty
The view gives values to these properties prior to recomputing the view’s body.
https://developer.apple.com/documentation/swiftui/dynamicproperty
Your Size struct isn’t a View so it can’t get values. In prior versions you would get an initial value and some updates but it was a bug, SwiftUI just started warning about the issue.
This is why most SwiftUI wrappers only work in views.
If you remove the wrapper from the Size struct the warnings will go away.

Related

Unable to connect WKExtensionDelegate in Xcode 14 watch app

In the Apple developer docs chapter "There and Back Again" the watch app's App is written like this:
#main
struct MyWatchApp: App {
#WKExtensionDelegateAdaptor(ExtensionDelegate.self) var extensionDelegate
#SceneBuilder var body: some Scene {
WindowGroup {
NavigationView {
ContentView()
}
}
}
}
Unfortunately I get a purple runtime warning on my var declaration that says
#WKExtensionDelegateAdaptor should only be used within an extension based process
There must be something in Xcode that explicitly defines the App structure as "extension-based" but I can't find it!
Edit: More clarification... I am trying to handle the special method that gets called after you run the HealthKit method startWatchApp(with:completion:)
The special method for watch extensions is func handle(_ workoutConfiguration: HKWorkoutConfiguration)
I cannot seem to find a way to link this function on the new App structure for watch apps.
Ok, I found it. The solution is to simply replace WKExtensionDelegate with the new WKApplicationDelegate!
You can try this solution, it is simple and universal.
import WatchKit
class ExtensionDelegate: NSObject, WKExtensionDelegate {
static var current: ExtensionDelegate? {
return (WKExtension.shared().delegate as? ExtensionDelegate)
}
...
}
Then access this current instance like below, because it is Singleton, you can access it in the entire project scope.
ExtensionDelegate.current?.dosomething()

SwiftUI - How to get access to "WindowScene"

In watching the WWDC 21 videos reference StoreKit 2, there are a few functions that they reference wherein they let a value = WindowScene as follows:
func manageSubscriptions() async {
if let windowScene = self.view.window?.windowScene {
do {
try await AppStore.showManageSubscriptions(in: windowScene)
} catch {
//error
}
}
}
The let line errors out with the message: Type of expression is ambiguous without more context
If I try and provide more context with something like:
if let windowScene = (self.view.window?.windowScene)! as UIWindowScene {
I am told: Value of type 'MyStruct' has no member 'view'
What am I missing, must be something simple, to gain access to this needed UI element?
Thank you
Added:
I'd like to add that I am using a SwiftUI app that was created using a SceneDelegate and AppDelegate, not a simple struct: App, type of structure. So I am guessing I need to access something in the SceneDelegate to get the right object..
Just to provide an answer for anyone interested, with all credit to #aheze for finding it and #Matteo Pacini for the solution, to get this specific method to work when using a SwiftUI app that has an AppDelegate/SceneDelegate structure, this will work:
#MainActor
func manageSubscriptions() async {
if let windowScene = UIApplication.shared.connectedScenes.first {
do {
try await AppStore.showManageSubscriptions(in: windowScene as! UIWindowScene)
} catch {
//error
}
}
}
You can conversely use the view modifier manageSubscriptionsSheet(isPresented:) instead. This is Apple's recommended approach when using SwiftUI and will mitigate the need for getting a reference to the window scene.
Source:
If you’re using SwiftUI, call the manageSubscriptionsSheet(isPresented:)view modifier.

Protocols with associated types in Swift 4.2

I have a question about protocols with associated types, that occurred after updating to Xcode 10 and Swift 4.2.
Before I had a protocol:
protocol ViewModelBased: class {
associatedtype ViewModel
var viewModel: ViewModel { get set }
}
and a VC implementing it.
class MyViewController: UIViewController, ViewModelBased {
var viewModel: EntitiesViewModel!
}
After update to Xcode 10 I get and error saying MyViewController doesn't conform to the protocol and I have to declare the property as:
var viewModel: ViewModel! { get set }
Anyone has any idea why there is difference as I don't get it?
Basically your code was always dubious and now you’ve been caught:
protocol ViewModelBased: class {
associatedtype ViewModel
var viewModel: ViewModel { get set }
}
class MyViewController: UIViewController, ViewModelBased {
var viewModel: EntitiesViewModel!
}
In the protocol adopter MyViewController, what type do you claim corresponds to ViewModel? It seems you think it should be EntitiesViewModel. And the compiler permitted this to slide, allowing the implicitly unwrapped Optional wrapping a type to be substituted for the type itself.
But now there is no implicitly unwrapped Optional type; the type EntitiesViewModel! is effectively the same as the type EntitiesViewModel?, an Optional wrapping EntitiesViewModel. So if you want EntitiesViewModel to be ViewModel, and if you want this property’s type to be an Optional wrapping EntitiesViewModel, the protocol must declare this property’s type as an Optional wrapping ViewModel.

Call to swift method from JavaScript hangs xcode and application

I am writing an iOS App (using xcode 7.3 and swift 2.2) using JavascriptCode framework. Calling javascript methods from swift works perfect, but when I call the swift method from javascript, xcode simply shows a "loading" type of symbol and nothing happens. I need to "force quit" xcode to get out of this state.
I have followed https://www.raywenderlich.com/124075/javascriptcore-tutorial and http://nshipster.com/javascriptcore/ and I am trying pretty simple calls.
Has anyone faced this kind of issue?
My swift code is as follows:
#objc protocol WindowJSExports : JSExport {
var name: String { get set }
func getName() -> String
static func createWindowWithName(name: String) -> WindowJS
}
#objc class WindowJS : NSObject, WindowJSExports {
dynamic var name: String
init(name: String) {
self.name = name
}
class func createWindowWithName(name: String) -> WindowJS {
return WindowJS(name: name)
}
func getName() -> String {
NSLog("getName called from JS context")
return "\(name)"
}
}
I am initializing the context as follows:
runContext = JSContext()
runContext.name = "test_Context"
windowToJs = WindowJS(name: "test")
runContext.setObject(windowToJs.self, forKeyedSubscript: "WindowJS")
If I replace the last two lines in above code with below code without instantiating it, the code simply fails to load.
runContext.setObject(WindowJS.self, forKeyedSubscript: "WindowJS")
And the javascript code is as simple as
function check() {
return WindowJS.getName()
}
I do see the breakpoint being hit in the JS function check and when the WindowJS.getName gets called, xcode simply becomes unresponsive.
The setTimeout could be solved by adding following piece of code to my swift function.
let setTimeout: #convention(block) (JSValue, Int) -> () =
{ callback, timeout in
let timeVal = Int64(timeout)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, timeVal), dispatch_get_main_queue(), { callback.callWithArguments(nil)})
}
To expose this native code to the JS context, I also added following.
runContext.setObject(unsafeBitCast(setTimeout, AnyObject.self), forKeyedSubscript: "setTimeout")
Things then worked fine.
You're creating a deadlock since you are calling from Swift to JavaScript back to Swift. I'm not sure exactly why it is a deadlock but I had a similar issue with WKWebView on Mac recently.
You need to decouple this and make the communication asynchronous. This obviously means you cannot simply return a value from your JS function in this case.
To decouple, you can break the deadlock by deferring the work the JavaScript function needs to do out of the current runloop iteration using setTimeout:
function myFunction() {
setTimeout(function() {
// The actual work is done here.
// Call the Swift part here.
}, 0);
}
The whole native ↔︎ JavaScript communication is very, very tricky. Avoid it if you can. There's a project called XWebView that may be able to help you as it tries to ease bridging between the two worlds.

'#selector' refers to a method that is not exposed to Objective-C

The new Xcode 7.3 passing the parameter via addTarget usually works for me but in this case it's throwing the error in the title. Any ideas? It throws another when I try to change it to #objc
Thank you!
cell.commentButton.addTarget(self, action: #selector(FeedViewController.didTapCommentButton(_:)), forControlEvents: UIControlEvents.TouchUpInside)
The selector it's calling
func didTapCommentButton(post: Post) {
}
In my case the function of the selector was private. Once I removed the private the error was gone. Same goes for fileprivate.
In Swift 4
You will need to add #objc to the function declaration. Until swift 4 this was implicitly inferred.
You need to use the #objc attribute on didTapCommentButton(_:) to use it with #selector.
You say you did that but you got another error. My guess is that the new error is that Post is not a type that is compatible with Objective-C. You can only expose a method to Objective-C if all of its argument types, and its return type, are compatible with Objective-C.
You could fix that by making Post a subclass of NSObject, but that's not going to matter, because the argument to didTapCommentButton(_:) will not be a Post anyway. The argument to an action function is the sender of the action, and that sender will be commentButton, which is presumably a UIButton. You should declare didTapCommentButton like this:
#objc func didTapCommentButton(sender: UIButton) {
// ...
}
You'll then face the problem of getting the Post corresponding to the tapped button. There are multiple ways to get it. Here's one.
I gather (since your code says cell.commentButton) that you're setting up a table view (or a collection view). And since your cell has a non-standard property named commentButton, I assume it's a custom UITableViewCell subclass. So let's assume your cell is a PostCell declared like this:
class PostCell: UITableViewCell {
#IBOutlet var commentButton: UIButton?
var post: Post?
// other stuff...
}
Then you can walk up the view hierarchy from the button to find the PostCell, and get the post from it:
#objc func didTapCommentButton(sender: UIButton) {
var ancestor = sender.superview
while ancestor != nil && !(ancestor! is PostCell) {
ancestor = view.superview
}
guard let cell = ancestor as? PostCell,
post = cell.post
else { return }
// Do something with post here
}
Try having the selector point to a wrapper function, which in turn calls your delegate function. That worked for me.
cell.commentButton.addTarget(self, action: #selector(wrapperForDidTapCommentButton(_:)), forControlEvents: UIControlEvents.TouchUpInside)
-
func wrapperForDidTapCommentButton(post: Post) {
FeedViewController.didTapCommentButton(post)
}
As you know selector[About] says that Objective-C runtime[About] should be used. Declarations that are marked as private or fileprivate are not exposed to the Objective-C runtime by default. That is why you have two variants:
Mark your private or fileprivate method declaration by #objc[About]
Use internal, public, open method access modifier[About]

Resources