В AppDelegate у вас есть по стандарту:
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 active 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.
}
Где происходит сразу после переходного состояния, когда приложение находится в режиме переднего плана.
Как только это будет сделано, у вас появится еще одна проблема в вашем коде, вы создаете новый экземпляр вашего контроллера представления:
let vc = window?.rootViewController as! ViewController
if vc.refreshControl.isRefreshing {
vc.refreshControl.endRefreshing()
vc.refreshControl.beginRefreshing()
vc.testTableView.setContentOffset(CGPoint(x:0,y:vc.testTableView.contentOffset.y - vc.refreshControl.frame.size.height) , animated: true)
}
Это означает, что у вас есть новый экземпляр вашего refreshControl
, поэтому он еще не обновляется. Куда приведет ваш код, чтобы он никогда не работал.
Ниже вы можете найти полный код, чтобы заставить его работать после вашей реализации. Имейте в виду, что существуют разные способы сделать это без уведомлений. Вы можете использовать, например, метод viewWillAppear
. Но я использую делегат, как указано в вашем коде.
Ваш контроллер представления:
//
// ViewController.swift
// TestProject
//
// Created by Anish on 4/2/18.
// Copyright © 2018 Costello. All rights reserved.
//
import UIKit
var refreshControl = UIRefreshControl()
class ViewController: UIViewController {
@IBOutlet weak var testTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
testTableView.dataSource = self
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.resumeRefreshing), name: NSNotification.Name(rawValue: "resumeRefreshing"), object: nil)
addRefreshControl()
}
@objc func addRefreshControl() {
refreshControl.addTarget(self, action: #selector(refresh), for: .valueChanged)
refreshControl.tag = 1
testTableView.addSubview(refreshControl)
}
@objc func resumeRefreshing() {
refreshControl.endRefreshing()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
refreshControl.beginRefreshing()
self.testTableView.setContentOffset(CGPoint(x:0,y:-60) , animated: true)
}
}
@objc func refresh() {
print("isRefreshing")
}
}
extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 20
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = "Hello"
return cell
}
}
И ваш делегат:
//
// AppDelegate.swift
// TestProject
//
// Created by Costello on 4/2/18.
// Copyright © 2018 Costello. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationDidEnterBackground(_ application: UIApplication) {
}
func applicationDidBecomeActive(_ application: UIApplication) {
if refreshControl.isRefreshing {
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "resumeRefreshing"), object: nil)
//
}
}
}
person
GIJOW
schedule
02.04.2018