swift3 how to Change screen when app changes to background status - ios

in swift3
I want to change the screen to hide the original screen when the app is in the background state.
For example, if you press the home button twice while the app is running, the screen will change to a different screen.
I want to set the screen to change to LaunchScreen.
Thank you for your help.

Try this one:
func applicationDidEnterBackground(_ application: UIApplication) {
let imageView = UIImageView(frame: self.window!.bounds)
imageView.tag = 1001
imageView.image = UIImage(named: "") //your image goes here
UIApplication.shared.keyWindow?.subviews.last?.addSubview(imageView)
}
func applicationWillEnterForeground(_ application: UIApplication) {
if let imageView : UIImageView = UIApplication.shared.keyWindow?.subviews.last?.viewWithTag(1001) as? UIImageView {
imageView.removeFromSuperview()
}
}

"If you do not want your application to remain in the background when it is quit, you can explicitly opt out of the background execution model by adding the UIApplicationExitsOnSuspend key to your application’s Info.plist file and setting its value to YES.
When an application opts out, it cycles between the not running, inactive, and active states and never enters the background or suspended states.
When the user taps the Home button to quit the application, the applicationWillTerminate: method of the application delegate is called and the application has approximately five seconds to clean up and exit before it is terminated and moved back to the not running state."
s

Add this function in your AppDelegate.
func applicationWillResignActive(_ application: UIApplication) {
// Change the view to show what you want here.
}
This method is called to let your app know that it is about to move
from the active to inactive state. This can occur for certain types of
temporary interruptions (such as an incoming phone call or SMS
message) or when the user quits the app and it begins the transition
to the background state.
Source: https://developer.apple.com/reference/uikit/uiapplicationdelegate/1622950-applicationwillresignactive

This is common scenario where we want to avoid screen-shotting by iOS while going to BG or covering app screens when app is in stack.
Here is what I'm doing:
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
private var appCoverWindow: UIWindow?
private var appCoverVC: UIViewController?
func applicationDidBecomeActive(_ application: UIApplication) {
if appCoverWindow != nil {
appCoverWindow!.isHidden = true
appCoverWindow!.rootViewController = nil
appCoverWindow = nil
appCoverVC = nil
}
}
func applicationWillResignActive(_ application: UIApplication) {
appCoverVC = rootViewController().storyboard!.instantiateViewController(withIdentifier: "AppCoverVCId") as! AppCoverViewController
appCoverWindow = UIWindow(frame: UIScreen.main.bounds)
let existingTopWindow = UIApplication.shared.windows.last
appCoverWindow!.windowLevel = existingTopWindow!.windowLevel + 1
appCoverVC!.view.frame = appCoverWindow!.bounds
appCoverWindow!.rootViewController = appCoverVC!
appCoverWindow!.makeKeyAndVisible()
}
class func appLaunchImage() -> UIImage? {
//this method will return LaunchImage
let launchImageNames = Bundle.main.paths(forResourcesOfType: "png", inDirectory: nil).filter { (imageName) -> Bool in
return imageName.contains("LaunchImage")
}
for imageName in launchImageNames {
guard let image = UIImage(named: imageName) else { continue }
// if the image has the same scale and dimensions as the current device's screen...
if (image.scale == UIScreen.main.scale) && (image.size.equalTo(UIScreen.main.bounds.size)) {
return image
}
}
return nil
}
}
Instead of using UIWindow to cover app, we can directly use UIViewController also, but that may cause issues if keyboard is present while going to BG.
Here is AppCoverViewController.swift:
(It has XIB in storyboard with one full screen UIImageView)
class AppCoverViewController: BaseViewController {
#IBOutlet weak var bgImageView: UIImageView!//full screen image view
override func viewDidLoad() {
super.viewDidLoad()
if let image = AppDelegate.appLaunchImage() {
bgImageView.image = image
}
}
override func deviceOrientationDidChange() {
if let image = AppDelegate.appLaunchImage() {
bgImageView.image = image
}
}
}
This class takes care of device rotations also.

Related

I want to use "applicationWillEnterForeground", however my function requires an UIImageView and I can't call on it in AppDelegate?

I have an image on a website, and I want it to be put into a UIImageView, however I want it to refresh every time the application is launched.
I have the following code in a ViewController:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var image: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
get_image("WEBSITE.com/image.jpg", image)
}
func get_image(_ url_str:String, _ imageView:UIImageView)
{
let url:URL = URL(string: url_str)!
let session = URLSession.shared
let task = session.dataTask(with: url, completionHandler: {
(
data, response, error) in
if data != nil
{
let image = UIImage(data: data!)
if(image != nil)
{
DispatchQueue.main.async(execute: {
imageView.image = image
imageView.alpha = 0
UIView.animate(withDuration: 2.5, animations: {
imageView.alpha = 1.0
})
})
}
}
})
task.resume()
}
}
Since the image in WEBSITE.com/image.jpg is going to change often, I wan't the app to pull the image everytime it launches. I did some research, and was told to put the following code into my AppDelegate.
func applicationWillEnterForeground(_ application: UIApplication) {
ViewController().get_image("WEBSITE.com/image.jpg", image)
}
However, after the link, the "image" doesn't work. How do I reference the image in the AppDelegate file?
BTW, I get the following error message:
"Cannot convert value of type 'module' to expected argument type 'UIImageView'"
What do I do?
You can use the observer pattern to let ViewController know when the app will enter the foreground.
UIScene has a built in notification that you can simply observe from within the viewDidLoad of your view controller.
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(get_image), name: UIScene.willEnterForegroundNotification, object: nil)
}
The selector is the action taken whenever your view controller observes willEnterForegroundNotification. In order to use get_image as a selector you will also need to expose it to the Objective-C runtime by writing #Objc before the func keyword.

Need to switch SKScenes at applicationWillResignActive

I need to switch to my pause scene when I get applicationWillResignActive so the user cannot browse the background app screens without my timer running. I use the following code, but the switch to my pause scene doesn't happen until after I bring the app back into the foreground. What am I doing wrong?
func applicationWillResignActive(_ application: UIApplication) {
if let liveWindow = window {
if let viewController = liveWindow.rootViewController {
if let rotopathViewController = viewController as? RotopathViewController {
rotopathViewController.pause()
}
}
}
}
My view controller's pause function is simple.
func pause() {
game.score.pause()
rotopathView.presentScene(pausedScene)
}
and it just calls
func pause() {
elapsedTime += Int(round(Date().timeIntervalSince(intervalStartTime)))
isActive = false
}
If I move some code around and make sure that I set isActive = false after the presentScene call, there is no difference. Also, if I remove the isActive = false assignment, there is no difference.

ios - Dynamically edit 3d touch shortcut list

I want to add a "Continue" shortcut to my game. But when user will finish my game completely I want this to be either removed or replaced by another shortcut. Is this possible? I know 3d touch is handled by ios system, but maybe there are still some options
There are two ways to create shortcuts - dynamic and static.
Static are added to the plist and never change.
Dynamic can be added and removed in code.
It sounds like you want a dynamic shortcut, so here's roughly how you would do that:
To add:
if #available(iOS 9.0, *) {
if (UIApplication.sharedApplication().shortcutItems?.filter({ $0.type == "com.app.myshortcut" }).first == nil) {
UIApplication.sharedApplication().shortcutItems?.append(UIMutableApplicationShortcutItem(type: "com.app.myshortcut", localizedTitle: "Shortcut Title"))
}
}
To remove:
if #available(iOS 9.0, *) {
if let shortcutItem = UIApplication.sharedApplication().shortcutItems?.filter({ $0.type == "com.app.myshortcut" }).first {
let index = UIApplication.sharedApplication().shortcutItems?.indexOf(shortcutItem)
UIApplication.sharedApplication().shortcutItems?.removeAtIndex(index!)
}
}
You can then handle the shortcut by checking for it in the app delegate method:
#available(iOS 9.0, *)
func application(application: UIApplication, performActionForShortcutItem shortcutItem: UIApplicationShortcutItem, completionHandler: (Bool) -> Void) {
if shortcutItem.type == "com.app.myshortcut" {
// Do something
}
}
Don't forget to check for iOS9 and 3d Touch compatibility.
You can find Apple developer 3d touch pages here:
https://developer.apple.com/ios/3d-touch/
And specifically dynamic shortcuts here:
https://developer.apple.com/library/ios/samplecode/ApplicationShortcuts/Listings/ApplicationShortcuts_AppDelegate_swift.html#//apple_ref/doc/uid/TP40016545-ApplicationShortcuts_AppDelegate_swift-DontLinkElementID_3
Here's a handy class to trigger segues off of 3D touch off of your app icon. Of course you could trigger any action, but this is probably the most common. It then syncs itself when the app comes up or goes to the background. I'm using this to trigger a "My Projects" section only after the user has generated one (VisualizerProject.currentProject.images.count > 0).
class AppShortcut : UIMutableApplicationShortcutItem {
var segue:String
init(type:String, title:String, icon:String, segue:String) {
self.segue = segue
let translatedTitle = NSLocalizedString(title, comment:title)
let iconImage = UIApplicationShortcutIcon(templateImageName: icon)
super.init(type: type, localizedTitle:translatedTitle, localizedSubtitle:nil, icon:iconImage, userInfo:nil)
}
}
class AppShortcuts {
static var shortcuts:[AppShortcut] = []
class func sync() {
var newShortcuts:[AppShortcut] = []
//reverse order for display
newShortcuts.append(AppShortcut(type: "find-color", title: "Find Color", icon:"ic_settings_black_24px", segue: "showColorFinder"))
newShortcuts.append(AppShortcut(type: "samples", title: "Sample Rooms", icon:"ic_photo_black_24px", segue: "showSamples"))
//conditionally add an item like this:
if (VisualizerProject.currentProject.images.count > 0) {
newShortcuts.append(AppShortcut(type: "projects", title: "My Projects", icon:"ic_settings_black_24px", segue: "showProjects"))
}
newShortcuts.append(AppShortcut(type: "visualizer", title: "Paint Visualizer", icon:"ic_photo_camera_black_24px", segue: "showPainter"))
UIApplication.sharedApplication().shortcutItems = newShortcuts
shortcuts = newShortcuts
}
class func performShortcut(window:UIWindow, shortcut:UIApplicationShortcutItem) {
sync()
if let shortcutItem = shortcuts.filter({ $0.type == shortcut.type}).first {
if let rootNavigationViewController = window.rootViewController as? UINavigationController,
let landingViewController = rootNavigationViewController.viewControllers.first {
//Pop to root view controller so that approperiete segue can be performed
rootNavigationViewController.popToRootViewControllerAnimated(false)
landingViewController.performSegueWithIdentifier(shortcutItem.segue, sender: self)
}
}
}
}
Then in your app delegate, add the sync and perform shortcut calls
func applicationDidEnterBackground(application: UIApplication) {
AppShortcuts.sync()
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
AppShortcuts.sync()
}
#available(iOS 9.0, *)
func application(application: UIApplication, performActionForShortcutItem shortcutItem: UIApplicationShortcutItem, completionHandler: (Bool) -> Void) {
if let window = self.window {
AppShortcuts.performShortcut(window, shortcut: shortcutItem)
}
}
I assume you're talking about the so-called Quick Actions a user can call by force-touching your app's icon on his home screen. You can dynamically create and update them right from your code. The best way to learn about all the possibilities is looking at Apple's sample code.
[UIApplication sharedApplication].shortcutItems = #[];
worked for me. the other answer that suggests removing something from the array didn't work as shortcutItems is not mutable.

viewWillAppear is not being called after clicking the home button

i have this view controller
class ViewController: UIViewController {
override func viewWillAppear(animated: Bool) {
let user = NSUserDefaults()
let mobileNumber = user.valueForKey("mobileNumber") as? String
if let mobileNumber = mobileNumber {
print("mobile number = \(mobileNumber)")
}else {
print("no mobile number")
}
}
#IBAction func makePhoneCall(sender: UIButton) {
if let phoneCall = phoneCall {
let user = NSUserDefaults()
user.setValue(phoneCall, forKey: "mobileNumber")
when the user clicks on a button, i save the mobileNumber in nsuserdefault.
then i click the button, then i open the app again, but problem is that when i open the app agian, i don't bet any message from the viewWillAppear even though i am printing in the if and in the else part.
tylersimko is correct that viewWillAppear(_:) is not called when the application enters the foreground and that event is instead captured by "application will enter background".
That said, you don't need to observe this from the app delegate but could instead use the UIApplicationWillEnterForegroundNotification notification:
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "applicationDidEnterForeground", name: UIApplicationWillEnterForegroundNotification, object: nil)
}
func applicationDidEnterForeground() {
// Update variable here.
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
The above code:
When your view loads, your view controller registers to have the function applicationDidEnterForeground() called whenever the application enters the foreground.
The function applicationDidEnterForeground() does whatever needs to be done.
The view controller unregisters from all notifications when it deallocates to avoid a zombie reference in iOS versions before 9.0.
Given that you are working with NSUserDefaults, you could instead consider observing NSUserDefaultsDidChangeNotification.
In AppDelegate.swift, make your change in applicationWillEnterForeground:
func applicationWillEnterForeground(application: UIApplication) {
// do something
}
Alternatively, if you want to keep your changes in the ViewController, you could set up a function and call it like this:
func applicationWillEnterForeground(application: UIApplication) {
ViewController.refreshView()
}

App crash when reload button is pressed

i'm having some problems with my weather app for iOS.
I'm new in programming in xCode, so it could be a silly error.
Anyway, the problem is: I'm trying to add a refresh button in my Single Page App. The button has a IBAction function associated, so that when it is pressed it should get hidden and the activity indicator should appear.
That is the function:
#IBAction func reload() {
refreshButton.hidden = true
refreshActivityIndicator.hidden = false
refreshActivityIndicator.startAnimating()
}
and that is the declaration of the variables:
#IBOutlet weak var refreshButton: UIButton!
#IBOutlet weak var refreshActivityIndicator: UIActivityIndicatorView!
when i run the app and press the refresh button, the app crash and i get this error:
#UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { <--thread 1 signal sigarbt
the console doesn't show anything else.
What could be the problem?
// APPDELEGATE.SWIFT
import UIKit
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
application.setStatusBarHidden(true, withAnimation: .None)
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
//VIEWCONTROLLER.SWIFT
import UIKit
import Foundation
class ViewController: UIViewController {
private let apiKey = "447073dc853014a6fa37376c43d8462b"
#IBOutlet weak var iconView: UIImageView!
#IBOutlet weak var currentTimeLabel: UILabel!
#IBOutlet weak var temperatureLabel: UILabel!
#IBOutlet weak var humidityLabel: UILabel!
#IBOutlet weak var precipitationLabel: UILabel!
#IBOutlet weak var summaryLabel: UILabel!
#IBOutlet weak var refreshButton: UIButton!
#IBOutlet weak var refreshActivityIndicator: UIActivityIndicatorView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
refreshActivityIndicator.hidden = true
// base URL
let baseURL = NSURL(string: "https://api.forecast.io/forecast/\(apiKey)/")
// add coordinates to base url (API syntax)
let forecastURL = NSURL(string: "44.698150,10.656846", relativeToURL: baseURL)
// NSURL SESSION
//The NSURLSession class and related classes provide an API for downloading content via HTTP. This API provides a rich set of delegate methods for supporting authentication and gives your app the ability to perform background downloads when your app is not running or, in iOS, while your app is suspended. With the NSURLSession API, your app creates a series of sessions, each of which coordinates a group of related data transfer tasks. For example, if you are writing a web browser, your app might create one session per tab or window. Within each session, your app adds a series of tasks, each of which represents a request for a specific URL (and for any follow-on URLs if the original URL returned an HTTP redirect).
let sharedSession = NSURLSession.sharedSession()
let downloadTask : NSURLSessionDownloadTask = sharedSession.downloadTaskWithURL(forecastURL!, completionHandler:
{ (location: NSURL!, response: NSURLResponse!, error: NSError!) -> Void in
if (error == nil) {
let dataObject = NSData(contentsOfURL: location) // convert in NSData object
// serialize NSData object in Json as Dictionary
let weatherDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataObject!, options: nil, error: nil) as NSDictionary
// instance of Current (Current.swift) init with weatherDictionary
let currentWeather = Current(weatherDictionary: weatherDictionary)
// we put the code in the main queue cause this is relative the UI, that have the first thread (concurrency)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.temperatureLabel.text = "\(currentWeather.temperature)"
self.iconView.image = currentWeather.icon!
self.currentTimeLabel.text = "At \(currentWeather.currentTime!) it is"
self.humidityLabel.text = "\(currentWeather.humidity)"
self.precipitationLabel.text = "\(currentWeather.precipProbability)"
self.summaryLabel.text = "\(currentWeather.summary)"
// Stop refresh animation
self.refreshActivityIndicator.stopAnimating()
self.refreshActivityIndicator.hidden = true
self.refreshButton.hidden = false
})
}
})
downloadTask.resume() // call sharedSession.downloadTaskWithURL -> store json data in location (local temporary memory)
}
#IBAction func reload() {
println("PRESSED")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
I haven't got any .h or .m file.
Is reload function even getting called? If you are using storyboard/Xib for creating the UIButton then link the reload function in Xib on touchUpInside Event or if you are creating the UIButton event in code then like below:
Create another UIButton property in .h file:
#property(nonatomic, strong) UIButton *refresh;
In .m file
-(void) viewDidLoad {
self.refresh = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[self.refresh addTarget:self
action:#selector(reload:) forControlEvents:UIControlEventTouchUpInside];
[self.refresh setTitle:#"Reload" forState:UIControlStateNormal];
self.refresh .frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[self.view addSubview:self.refresh];
}
-(void) reload:(UIButton*)sender
{
NSLog(#"you clicked on button %#", sender.tag);
if(self.refresh.hidden) {
self.refresh.hidden = false;
} else {
self.refresh.hidden = true;
}
}
Okay it works!
Please don't ask me why :)
I simply deleted the code and rewrote it. And it works. Call it magic.
Thank you all for your answers.

Resources