lottie animation causing app crash on device - swiftui

I am using Lottie to display animations in application and I tried to use this animation
AnimationURL
LottieView -
struct LottieView: UIViewRepresentable {
var animationName: String
func makeUIView(context: UIViewRepresentableContext<LottieView>) -> UIView {
let view = UIView()
return view
}
func updateUIView(_ uiView: UIViewType, context: Context) {
let animationView = AnimationView()
let animation = Animation.named(animationName)
animationView.animation = animation
animationView.contentMode = .scaleAspectFit
animationView.backgroundBehavior = .pauseAndRestore
animationView.loopMode = .loop
animationView.translatesAutoresizingMaskIntoConstraints = false
uiView.addSubview(animationView)
NSLayoutConstraint.activate([
animationView.heightAnchor.constraint(equalTo: uiView.heightAnchor),
animationView.widthAnchor.constraint(equalTo: uiView.widthAnchor)
])
animationView.play()
}
}
But when I want to display animation, application crashes in AnimatorNode file from Lottie library in this function (Thread 1: EXC_BAD_ACCESS (code=2, address=0x16ce6bff0)):
func updateContents(_ frame: CGFloat, forceLocalUpdate: Bool) -> Bool {
guard isEnabled else {
return parentNode?.updateContents(frame, forceLocalUpdate: forceLocalUpdate) ?? false
}
}
When I opened View Hierarchy after app crash, I received this log -
Failed to unarchive request data with error: Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set. around line 1, column 0." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set. around line 1, column 0., NSJSONSerializationErrorIndex=0}
On simulator, animation is running normally, but when I build application on device, application is crashing on this animation. Is there any way to fix this and use this animation?

We ran into the same issue.
It doesn't depend on SwiftUI / UIKit thing.
On Simulator it works ok because your simulator has more memory than iPhone does. So maybe your animation.json is too hard for current version of Lottie-ios lib. Maybe its good idea to report them, that they should update implementation of lib on iOS side.
Thank you!

Related

Swiftui list: trigger an action on tap and mimic basic select then auto-unselect

I'm starting to learn swiftui and I've run into a problem that is both very basic and easily solvable in UIKit; but after spending days searching the internet and watching WWDC videos I've found no native solution.
The premise is simple: I have an array of songs I want to display in a list; when a user taps on a song view it should highlight the view on press, unhighlight after release, and then play the song (ie trigger an action). Sounds simple right?
Here's what I tried and spent way too much time on:
Using List(selection) + .onEvent(changed): I end up with a UUID (because i've only gotten selection to work with a UUID) that I then have to check against an array of songs to match AND the cell won't unhighlight/select itself; even when I try to manually set the State variable to nil or another generated UUID.
Using .onTap (either on or in the cell): I have to tap on the text of the cell to trigger onTap so I get a lot of taps that just don't work (because I have lots of white space in the cell). I also don't get a nice UI color change on press/release.
So after spending hours trying many different things I've finally come up with a solution and I basically wanted to create an account and share it to hopefully help other developers in my position. Because this so very annoyed me that something so basic took so much effort and time to do.
In the end the best solution I came up with was this:
Using ZStack and an empty button:
edit: I found I need to include and hide the content otherwise the button doesn't grow to fill the space (seems in lists it does for some reason). Though not sure what the hit on performance is of rendering the content twice when hiding it. Maybe a GeometryReader would work better?
struct SelectionView: ViewModifier {
let onSelect: () -> Void
func body(content: Content) -> some View {
ZStack (alignment: .leading) {
Button {
onSelect()
} label: {
content
.hidden()
}
content
}
}
}
extension View {
func onSelection(_ selection: #escaping () -> Void) -> some View {
self.modifier(SelectionView(onSelect: selection))
}
}
then to use it:
SongCell(song: song)
.onSelection {
// Do whatever action you want
}
No messing around with list selection, no weird tap hit boxes, and get the press/release color change. Basically put an empty button in a ZStack and trigger off it's action. Could possibly cause tap/touch issues with more complicated cells (?) but it does exactly what I need it to do for my basic app. I'm just not sure why it took so much effort and why apple doesn't support such a basic use case by default? If I've overlooked something native please do inform me. Thanks.
I got the basic idea what you are trying to do. I'm Going to show simple example. Maybe using this you will be able to find proper solution.
First let's create a color : -
#State var colorToShow : Color = Color.blue
Now in body we have our ZStack or Your cell that we want to deal with : -
ZStack{
colorToShow
}.frame(width: 50, height: 50).padding()
.onLongPressGesture(minimumDuration: 3) {
print("Process Complete")
colorToShow = .green
} onPressingChanged: { pressing in
if pressing {
print("Pressing")
colorToShow = .red
} else {
print("Pressing Released")
colorToShow = .blue
}
}
Here we are using .onLongPressGesture. You can set minimum duration on which you want to perform action. Now on process completion You set what you want to do. OnPressingChange give you a bool value that changes according to user is pressing that button or not. Show color change(Highlight) or do action while bool value is true. When user release button do action or unhighlight since bool value turns false.
Hope you find it useful.

present SwiftUI view from a SKScene

Is it possible to present a SwiftUI view from a SpriteKit scene?
I have various sprites in the game scene. When certain one receive touch data I want a SwiftUI view to pop up.
In the past I have used something like this to present another UI view.
if bloqsLogo.contains(location) {
if instructionsOn == false {
let pop = InstructionsPopUp()
pop.tag = 104
self.view?.addSubview(pop)
instructionsOn = true
} else
if instructionsOn == true {
if let viewWithTag = self.view!.viewWithTag(104) {
viewWithTag.removeFromSuperview()
instructionsOn = false
}else{
print("nah")
}
}
}
My SKScene is an instance of another SwiftUI view and presented there. A good part of my GUI is done in SwiftUI. I am basically wanting to code as much of my App as I can in SwiftUI while keeping the physics and sprites in a SKScene. All of which is going rather well besides this!

SwiftUI change output format of `Text` using as `.timer`

Is there a way to change the output format of a Text using init(_ date: Date, style: Text.DateStyle)?
Using a .timer, the output is like: 0:42, but I want something like 00:00:42.
Background
I want to create a widget (iOS 14) where a timer is running, and as I think it's not a good idea to trigger a widget update every second, and this may even also not work reliably, at least that's not how widget are indented to be used.
So I thought about using this predefined timer functionality of Text.
I'm quite new to SwiftUI and don't really know about all the capabilities yet. So maybe I could create a similar custom Text-View by myself? Any ideas on how to achieve this?
Or asked differently: Is there a way to create such self-updating components by oneself, that also work in an iOS 14 widget? (Seems like using Timer.publish to update the View does not work in an iOS 14 widget)
No solution => Workaround
As of today, there doesn't seem to be a proper solution for this. But as the interest in a "solution" or workaround for this seems to be there, I'll just post what I ended up with, for now.
Code
Basically I just manually update the Text once a second, and calculate the difference from the reference date to "now".
struct SomeView: View {
let referenceDate = Date() // <- Put your start date here
#State var duration: Int = 0
let timer = Timer.publish(every: 1, on: .current, in: .common).autoconnect()
var body: some View {
Text(self.duration.formatted(allowedUnits: [.hour, .minute, .second]) ?? "")
.onReceive(self.timer) { _ in
self.duration = referenceDate.durationToNow ?? 0
}
}
}
extension Date {
var durationToNow: Int? {
return Calendar.current
.dateComponents([.second], from: self, to: Date())
.second
}
}
extension Int {
func formatted(allowedUnits: NSCalendar.Unit = [.hour, .minute]) -> String? {
let formatter = DateComponentsFormatter()
formatter.allowedUnits = allowedUnits
formatter.zeroFormattingBehavior = .pad
return formatter.string(from: DateComponents(second: self))
}
}
WidgetKit limitations
This unfortunately does not work for WidgetKit, as the timer does not run or at least the UI does not refresh. So I ended up, only displaying minutes in the widget (which is kinda ok for my purpose) and just set an update in the "timeline" for each minute.

Google Sign In showing blank screen in iOS

I have implemented code as per the google SDK documentation line by line in my app, but still when I click on google sign in button app shifts to new view controller with webview with blank screen. Have tried multiple solution found here : GIDSignIn white screen on iOS 91. But no lucks with resolving the problem , have attached the screen shot for getting closer look about the screen.
Following are the pods that I'm using,
Running XCode 9.1, iOS 10.0 and later. Kindly request someone to help.
Update: View Hierarchy
Update: viewDidLoad's code:
GIDSignIn.sharedInstance().uiDelegate = self
if self.isChangePassword {
self.addSignInView()
}
else {
self.addSignUpView()
}
fileprivate func addSignInView() {
guard let signInEmailView: SignInEmailView = Bundle.main.loadNibNamed(NibNames.SignInEmailView.rawValue, owner: self, options: nil)?[0] as? SignInEmailView
else {
return
}
signInEmailView.delegate = self
gaManager.trackScreen(screenName: ScreenNames.SignIn.rawValue)
self.animateView(signInEmailView)
}
fileprivate func addSignInView() {
guard let signInEmailView: SignInEmailView = Bundle.main.loadNibNamed(NibNames.SignInEmailView.rawValue, owner: self, options: nil)?[0] as? SignInEmailView
else {
return
}
signInEmailView.delegate = self
gaManager.trackScreen(screenName: ScreenNames.SignIn.rawValue)
self.animateView(signInEmailView)
}
I have the same problem. I use the UIAlertView to confirm user really want to do authorization. It will show the blank screen. If I remove the UIAlertView and show the authorization view directly. It works fine.
The problem also show in the Dropbox authorization screen.
If you not use UIAlertView , please try to pass the top most controller
https://github.com/dropbox/dropbox-sdk-obj-c/issues/182
Hope this can do some help.
Finally after so many days found the problem. I was showing splash view from my appDelegate using refrence of UIWindow which was adding and removing an imgview as subview to the window. So it was somehow messing with the UINavigation's stack and my view controller was not getting any reference to the UINavigationController. After removing that code it's working just fine. Also came to the solution that, if I want to show splash screen, as I can't use UIWindow's reference, I have to add new VC and write my all navigation code there. #TedYu Thank you very much for the help. :)

iOS 11 inputAccessoryView broken

I have the following set up for my UIToolBar / Accessory View on a view controller
#IBOutlet var inputFieldView: UIToolbar!
override var canBecomeFirstResponder: Bool{
return true
}
override var inputAccessoryView: UIView?{
return self.inputFieldView
}
then inside my viewDidLoad I have:
let seperator = UIView(frame: CGRect(x:0 , y: 0, width: ScreenSize.width(), height: 1))
seperator.backgroundColor = UIColor.lightBackground
self.inputFieldView.addSubview(seperator)
self.inputFieldView.isTranslucent = false
self.inputFieldView.setShadowImage(UIImage(), forToolbarPosition: .any)
self.inputFieldView.setBackgroundImage(UIImage(), forToolbarPosition: .any, barMetrics: .default)
self.inputFieldView.removeFromSuperview()
This worked great for ios versions 10 and 9. It is a text view with a "Send" button. It sits at the bottom of the screen and when pressed, becomes first responder allowing the keyboard to come up and it positions itself correctly.
With ios 11 i cannot even click on it when it is at the bottom, so I cannot type at all.
This is a known bug on iOS 11. UIToolbar subviews don't get the touch events because some internal views to the toolbar aren't properly setup.
The current workaround is to call toolBar.layoutIfNeeded() right before adding subviews.
In your case:
inputFieldView.layoutIfNeeded()
Hopefully this will get fixed on the next major version.
Solved it. It looks like UIToolbar's just are not working correctly in iOS 11.
Changed it to an UIView and removed
self.inputFieldView.isTranslucent = false
self.inputFieldView.setShadowImage(UIImage(), forToolbarPosition: .any)
self.inputFieldView.setBackgroundImage(UIImage(), forToolbarPosition: .any, barMetrics: .default)
got it working (and changed it to a UIView from UIToolbar in the xib as well.)