UIProgressView as health bar and update when button pressed. Swift - ios

So I started making a game and I wanted to use a progress bar as a health bar for many different things and I couldn't figure out why it wasn't updating at all. It did, however, update in the viewdidload function. Here is the code that I am using.
func updateHealthBars() {
hullHealthBar.setProgress(hullHealth/hullHealthMax, animated: true)
cannonsHealthBar.setProgress(cannonsHealth/cannonsHealthMax, animated: true)
sailsHealthBar.setProgress(sailsHealth/sailsHealthMax, animated: true)
crewHealthBar.setProgress(crewHealth/crewHealthMax, animated: true)
}
#IBAction func setSailButton(sender: AnyObject) {
if hullHealth > 0 {
hullHealth-=20
}
else if cannonsHealth > 0 {
cannonsHealth-=20
}
else if sailsHealth > 0 {
sailsHealth-=20
}
else if crewHealth > 0 {
crewHealth-=20
}
updateHealthBars()
}
If anybody knows what I need to do to update their health when I press the button, I would be very thankful because I have been trying to do this for a while now without success. I am using XCode 6.

In Swift, when assigning numbers using literals without decimals, it uses Int. ProgressView requires floats. Try the following:
func updateHealthBars() {
dispatch_async(dispatch_get_main_queue(), ^{
hullHealthBar.setProgress(hullHealth/hullHealthMax, animated: true)
cannonsHealthBar.setProgress(cannonsHealth/cannonsHealthMax, animated: true)
sailsHealthBar.setProgress(sailsHealth/sailsHealthMax, animated: true)
crewHealthBar.setProgress(crewHealth/crewHealthMax, animated: true)
});
}
#IBAction func setSailButton(sender: AnyObject) {
if hullHealth > 0.0 {
hullHealth-=20.0
}
else if cannonsHealth > 0.0 {
cannonsHealth-=20.0
}
else if sailsHealth > 0.0 {
sailsHealth-=20
}
else if crewHealth > 0.0 {
crewHealth-=20.0
}
updateHealthBars()
}
Make sure your properties are also floats:
var hullHealth: Float = 0 or var hullHealth = 0.0

I finally got this to work. So my original code worked. The actual problem was something to do with my button not being connected right or something even though everything else worked fine. I made a new button and put the same things in it and it worked fine. It was a problem with the button, not the thread or anything.

Related

UIViewController dismiss issue

I want to wait until dismiss animation completes but I don't want to use many blocks in my code, so I wrote this function in UIViewController extension (almost like this worked several years ago for me):
func dismissAnimated() {
var comleted: Bool = false
self.dismiss(animated: true) {
comleted = true
}
while !comleted {
RunLoop.current.run(mode: RunLoop.Mode.common, before: Date.distantFuture)
}
}
so now instead of:
viewController.dismiss(animated: true) {
// code after completion
}
I was supposed to write:
viewController.dismissAnimated()
// code after completion
But it doesn't dismiss view controller and doesn't enter into completion block.
I tried different RunLoop modes, tried different dates, tried inserting RunLoop.current.run into while condition, it didn't work. Any ideas how to accomplish this?
Edit:
And it worked on iOS 9 or something like this (may be with some code changes, because I can't find my source code). I start RunLoop.current.run to avoid blocking main thread. For instance, if I put completed = true in DispatchQue.main.asyncAfter , it will work, the issue is with dismiss
I tried again because I was curious and this solution actually works for me:
#objc private func dismissTapped() {
let dismissalTime = dismissAnimated()
print("Dismissal took: %ld", abs(dismissalTime))
}
private func dismissAnimated() -> TimeInterval {
let startDate = Date()
var completed = false
self.dismiss(animated: true) {
completed = true
}
while !completed {
RunLoop.current.run(mode: .default, before: .distantFuture)
}
return startDate.timeIntervalSinceNow
}
iOS 12.1.2 | Swift 4.2
It doesn't dismiss because your while !completed loop has stalled the main thread and the UI update happens on the main thread. What is wrong with running whatever code you need to run inside the dismiss completion closure?
self.dismiss(animated: true) {
runSomeCode()
}
If it's really just about not using blocks maybe this may be a solution?
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
if self.navigationController?.isBeingDismissed ?? self.isBeingDismissed {
print("Dismissal completed...")
}
}

Switch Save user preference

I am trying to send a tag with OneSignal when the switch is turned on, and send request to delete the tag when it is turned off again.
#IBAction func tagGeneral(_ sender: UISwitch) {
if (sender.isOn == true) {
OneSignal.sendTag("General", value: "value")
print("sendtag")
}
else {
OneSignal.deleteTag("General")
print("deletetag")
}
}
This is the code i use for it. Seems to be working but when the user goes to another page the switch is automatically turned off...
How can i fix this?
Regarding #Ryan's comment, Here's an answer:
First. there are many ways to save the user preference, i'll be doing it with UserDefaults() | Edit your button action code:
#IBAction func tagGeneral(_ sender: UISwitch) {
let userdef = UserDefaults.standard
if (sender.isOn == true) {
OneSignal.sendTag("General", value: "value")
print("sendtag")
// user made the choice
userdef.set(true, forKey: "sw_set")
} else {
OneSignal.deleteTag("General")
print("deletetag")
// reset
userdef.set(false, forKey: "sw_set")
}
}
Normally this wouldn't work without this little function, make sure you call this function in your viewDidAppear():
private func init_switch() {
// Thanks #Vadian for the tip
let userdef = UserDefaults.standard
self.yourSwitch.isOn = userdef.bool(forKey: "sw_set")
}
Call it in viewDidAppear():
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)
self.init_switch()
}
And let me know if it helped.

Sinch is not supporting video call in swift

here is my code. I covert this code from objective c to swift from the sinch test` Giving the Objective-C part might be interesting to help but it's not supporting video call. when i accept the call audio is working fine. but video is not sending to the other device. please help me out if any one has the sample code for swift then send or try to fix it with this code.. thanks
// MARK: - Load
override func viewDidLoad() {
super.viewDidLoad()
if call?.direction == SINCallDirection.incoming {
self.callStateLabel.text = ""
self.showButtons(EButtonsBar.kButtonsAnswerDecline)
//audioController().startPlayingSoundFile(path(forSound: "incoming.wav"), loop: true)
} else {
self.callStateLabel.text = "calling..."
self.showButtons(EButtonsBar.kButtonsHangup)
}
if (call?.details.isVideoOffered)! {
localVideoView.addSubview(videoController().localView())
localVideoFullscreenGestureRecognizer.require(toFail: switchCameraGestureRecognizer)
videoController().localView().addGestureRecognizer(localVideoFullscreenGestureRecognizer)
videoController().remoteView().addGestureRecognizer(remoteVideoFullscreenGestureRecognizer)
}
}
#IBAction func accept(sender: AnyObject) {
call?.answer()
}
#IBAction func decline(sender: AnyObject) {
call?.hangup()
dismiss(animated: true, completion: nil)
}
#IBAction func hangup(sender: AnyObject) {
call?.hangup()
dismiss(animated: true, completion: nil)
}
func audioController() -> SINAudioController{
return Global.client.audioController()
}
func videoController() -> SINVideoController {
return Global.client.videoController()
}
Add 2 Views in your view controller. One is for local video view and another one is for remote video video. Set it outlets to view controller. I have a working audio call example and i just add this things to my call view controller.
func videoController() -> SINVideoController {
return appDeletgate.client.videoController()
}
In viewdidload check for if video is offered by call.
if call.details.isVideoOffered {
localVideoView.addSubview(videoController().localView())
//localVideoFullscreenGestureRecognizer.require(toFail: switchCameraGestureRecognizer)
//videoController().localView().addGestureRecognizer(localVideoFullscreenGestureRecognizer)
//videoController().remoteView().addGestureRecognizer(remoteVideoFullscreenGestureRecognizer)
}
Add this method to add remote video in view.
func callDidAddVideoTrack(_ call: SINCall?) {
remoteVideoView.addSubview(videoController().remoteView())
}
Also make sure you add this 2 keys into info.plist
<key>NSCameraUsageDescription</key>
<string>$(PRODUCT_NAME) need to access your camera for video call.</string>
<key>NSMicrophoneUsageDescription</key>
<string>$(PRODUCT_NAME) uses the Microphone for calling</string>
And this is finally how i call it.
let call: SINCall? = self.callClient().callUserVideo(withId: recipientName) //self.callClient().callUser(withId: recipientName)
let callVC = mainStoryBoard.instantiateViewController(withIdentifier: "CallVC") as! CallVC
callVC.call = call
self.navigationController?.pushViewController(callVC, animated: true)

CNContactViewController Cancel Button Not Working

I'm trying to use the built-in new contact UI and am getting unexpected behavior with the cancel button. The code below works and calls up the new contact screen but the cancel button will only clear the screen entries not cancel out of the new contact screen. In the built in contacts app hitting cancel returns to the contact list screen. I would like the cancel button to close out the window.
#IBAction func newTwo(sender: AnyObject) {
AppDelegate.getAppDelegate().requestForAccess { (accessGranted) -> Void in
if accessGranted {
let npvc = CNContactViewController(forNewContact: nil)
npvc.delegate = self
self.navigationController?.pushViewController(npvc, animated: true)
}
}
}
did you implement CNContactViewControllerDelegate methods?
Here's a link to documentation
for example:
func contactViewController(viewController: CNContactViewController, didCompleteWithContact contact: CNContact?) {
self.dismissViewControllerAnimated(true, completion: nil)
}
It worked for me using the following code:
Swift 3
func contactViewController(_ vc: CNContactViewController, didCompleteWith con: CNContact?) {
vc.dismiss(animated: true)
}
Also I changed the way I was calling the controller:
Instead of:
self.navigationController?.pushViewController(contactViewController, animated: true)
the solution was:
self.present(UINavigationController(rootViewController: contactViewController), animated:true)
I found the solution using the example code Programming-iOS-Book-Examples written by Matt Neuburg:
Better way to do the dismissing would be to check if the contact is nil and then dismiss it. The dismiss doesn't work if you've pushed the view controller from a navigation controller. You might have to do the following:
func contactViewController(viewController: CNContactViewController, didCompleteWithContact contact: CNContact?) {
if let contactCreated = contact
{
}
else
{
_ = self.navigationController?.popViewController(animated: true)
}
}

navigation ios 8 swift?

I am new to the IOS world. I having trouble changing view when im switching to a new view which only can be shown when I login. I am using inside the loginfuction:
#IBAction func loginVerification(sender: UIButton!) {
//Check with the cloud
//temporary faking credentials
var user = "n"
var pass = "n"
if usernameLogin.text == user &&
passwordLogin.text == pass
{
println("Correct credentials")
let homeviewcontroller = HomeViewController()
self.presentViewController(homeviewcontroller, animated: true, completion: nil)
}
else
{
println("Wrong credentials!!")
}
}
The function above is triggered when I press the login button which checks for credentials.
Using the lines above makes the view black. Any suggestions on how to make it work? Any tutorial I can follow on navigation between views? And please don't be so hard on me :)
Thanks in advance!
Hi I would try the Apple tutorials - they are fairly well written and have code samples. Here is one that I used when I was learning: https://developer.apple.com/library/ios/referencelibrary/GettingStarted/RoadMapiOS/SecondTutorial.html. This one is specifically about navigating using Storyboards and Segues. If you look on the left of the page, you'll see links to other tutorials that may be helpful for you when getting started.
Try the following code:
let controller: homeviewcontroller = self.storyboard?.instantiateViewControllerWithIdentifier("homeviewcontroller") as! homeviewcontroller
self.presentViewController(controller, animated: true, completion: nil)
#IBAction func loginVerification(sender: UIButton!) {
//Check with the cloud
//temporary faking credentials
var user = "n"
var pass = "n"
if usernameLogin.text == user &&
passwordLogin.text == pass
{
println("Correct credentials")
let controller: homeviewcontroller = self.storyboard?.instantiateViewControllerWithIdentifier("homeviewcontroller") as! homeviewcontroller
self.presentViewController(controller, animated: true, completion: nil)
}
else
{
println("Wrong credentials!!")
}
}

Resources