How to Display an Activity Indicator With Text on iOS 8 With Swift

How to display an activity indicator with text on iOS 8 with Swift?

Xcode 9.0 • Swift 4.0



import UIKit
class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var filterButton: UIButton!
@IBOutlet weak var saveButton: UIButton!
let destinationUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
.appendingPathComponent("filteredImage.png")
let imagePicker = UIImagePickerController()
let messageFrame = UIView()
var activityIndicator = UIActivityIndicatorView()
var strLabel = UILabel()
let effectView = UIVisualEffectView(effect: UIBlurEffect(style: .dark))
func activityIndicator(_ title: String) {
strLabel.removeFromSuperview()
activityIndicator.removeFromSuperview()
effectView.removeFromSuperview()
strLabel = UILabel(frame: CGRect(x: 50, y: 0, width: 160, height: 46))
strLabel.text = title
strLabel.font = .systemFont(ofSize: 14, weight: .medium)
strLabel.textColor = UIColor(white: 0.9, alpha: 0.7)
effectView.frame = CGRect(x: view.frame.midX - strLabel.frame.width/2, y: view.frame.midY - strLabel.frame.height/2 , width: 160, height: 46)
effectView.layer.cornerRadius = 15
effectView.layer.masksToBounds = true
activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .white)
activityIndicator.frame = CGRect(x: 0, y: 0, width: 46, height: 46)
activityIndicator.startAnimating()
effectView.contentView.addSubview(activityIndicator)
effectView.contentView.addSubview(strLabel)
view.addSubview(effectView)
}
func saveImage() {
do {
try imageView.image?.data?.write(to: destinationUrl, options: .atomic)
print("file saved")
} catch {
print(error)
}
}
func applyFilterToImage() {
imageView.image = imageView.image?.applying(contrast: 1.5)
}
override func viewDidLoad() {
super.viewDidLoad()
guard let url = URL(string: "https://upload.wikimedia.org/wikipedia/commons/a/a8/VST_images_the_Lagoon_Nebula.jpg"), let data = try? Data(contentsOf: url), let image = UIImage(data: data) else { return }
view.backgroundColor = UIColor(white: 0, alpha: 1)
imageView.image = image
}
@IBAction func startSavingImage(_ sender: AnyObject) {
saveButton.isEnabled = false
filterButton.isEnabled = false
activityIndicator("Saving Image")
DispatchQueue.main.async {
self.saveImage()
DispatchQueue.main.async {
self.effectView.removeFromSuperview()
self.saveButton.isEnabled = true
self.filterButton.isEnabled = true
}
}
}
@IBAction func filterAction(_ sender: AnyObject) {
filterButton.isEnabled = false
saveButton.isEnabled = false
activityIndicator("Applying Filter")
DispatchQueue.main.async {
self.applyFilterToImage()
DispatchQueue.main.async {
self.effectView.removeFromSuperview()
self.filterButton.isEnabled = true
self.saveButton.isEnabled = true
}
}
}
@IBAction func cameraAction(_ sender: AnyObject) {
if UIImagePickerController.isSourceTypeAvailable(.camera) {
imagePicker.delegate = self
imagePicker.sourceType = .camera
present(imagePicker, animated: true)
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [AnyHashable: Any]!) {
dismiss(animated: true, completion: nil)
imageView.image = image
}
}


extension Data {
var image: UIImage? { return UIImage(data: self) }
}


extension UIImage {
var data: Data? { return UIImagePNGRepresentation(self) }
func applying(contrast value: NSNumber) -> UIImage? {
guard let ciImage = CIImage(image: self)?.applyingFilter("CIColorControls", withInputParameters: [kCIInputContrastKey: value]) else { return nil }
UIGraphicsBeginImageContextWithOptions(size, false, scale)
defer { UIGraphicsEndImageContext() }
UIImage(ciImage: ciImage).draw(in: CGRect(origin: .zero, size: size))
return UIGraphicsGetImageFromCurrentImageContext()
}
}


How to add activity indicator to UITextView?

You should not use Data contents Of URL initializer to download data synchronously. There is no guarantee it will succeed. You need to download your data asynchronously using NSURLSession method dataTaskWithURL as I have already suggested to you at your last question. Regarding your new question it has been already answered here. Combining both answers you should be able to accomplish what you are trying to. More info commented at the code bellow::

import UIKit
class ViewController: UIViewController {
@IBOutlet var textview2: UITextView!
// declare your activityIndicator
let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .white)
// you will need a new view for your activity indicator and a label for your message
let messageFrame = UIView()
let strLabel = UILabel(frame: CGRect(x: 50, y: 0, width: 160, height: 50))
func displayActivityIndicator() {
strLabel.text = "Loading file"
strLabel.textColor = .white
messageFrame.layer.cornerRadius = 15
messageFrame.backgroundColor = UIColor(white: 0, alpha: 0.7)
activityIndicator.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
activityIndicator.startAnimating()
messageFrame.addSubview(activityIndicator)
messageFrame.addSubview(strLabel)
view.addSubview(messageFrame)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// set your message frame (you can also position it using textview2.frame
messageFrame.frame = CGRect(x: view.frame.midX - 80, y: view.frame.midY - 25 , width: 160, height: 50)
// call your activity indicator method
displayActivityIndicator()
// call your method to download your data asynchronously
getRTFData(from: "http://thewalter.net/stef/software/rtfx/sample.rtf", textview2)
}
func getRTFData(from link: String,_ textView: UITextView) {
// make sure your link is valid NSURL using guard
guard let url = URL(string: link) else { return }
// creata a data task for your url
URLSession.shared.dataTask(with: url) {
(data, response, error) in
// use guard to make sure you get a valid response from the server and your data it is not nil and you got no errors otherwise return
guard
let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
let data = data, error == nil
else { return }
// you need to use dispatch async to update the UI
DispatchQueue.main.async {
// stop animating the activity indicator and remove the messageFrame from the view
self.activityIndicator.stopAnimating()
self.messageFrame.removeFromSuperview()

// NSAttributedString data initialiser throws an error so you need to implement Do Try Catch error handling
do {
textView.attributedText = try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil)
textView.isEditable = false
} catch {
print(error)
}
}
}.resume()
}
override func viewDidLoad() {
super.viewDidLoad()
}
}

How to display activity indicator in middle of the iphone screen?

UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc]     
initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];

activityView.center=self.view.center;
[activityView startAnimating];
[self.view addSubview:activityView];

How to display an activity indicator with text on iOS 8 with Swift?

Xcode 9.0 • Swift 4.0



import UIKit
class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var filterButton: UIButton!
@IBOutlet weak var saveButton: UIButton!
let destinationUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
.appendingPathComponent("filteredImage.png")
let imagePicker = UIImagePickerController()
let messageFrame = UIView()
var activityIndicator = UIActivityIndicatorView()
var strLabel = UILabel()
let effectView = UIVisualEffectView(effect: UIBlurEffect(style: .dark))
func activityIndicator(_ title: String) {
strLabel.removeFromSuperview()
activityIndicator.removeFromSuperview()
effectView.removeFromSuperview()
strLabel = UILabel(frame: CGRect(x: 50, y: 0, width: 160, height: 46))
strLabel.text = title
strLabel.font = .systemFont(ofSize: 14, weight: .medium)
strLabel.textColor = UIColor(white: 0.9, alpha: 0.7)
effectView.frame = CGRect(x: view.frame.midX - strLabel.frame.width/2, y: view.frame.midY - strLabel.frame.height/2 , width: 160, height: 46)
effectView.layer.cornerRadius = 15
effectView.layer.masksToBounds = true
activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .white)
activityIndicator.frame = CGRect(x: 0, y: 0, width: 46, height: 46)
activityIndicator.startAnimating()
effectView.contentView.addSubview(activityIndicator)
effectView.contentView.addSubview(strLabel)
view.addSubview(effectView)
}
func saveImage() {
do {
try imageView.image?.data?.write(to: destinationUrl, options: .atomic)
print("file saved")
} catch {
print(error)
}
}
func applyFilterToImage() {
imageView.image = imageView.image?.applying(contrast: 1.5)
}
override func viewDidLoad() {
super.viewDidLoad()
guard let url = URL(string: "https://upload.wikimedia.org/wikipedia/commons/a/a8/VST_images_the_Lagoon_Nebula.jpg"), let data = try? Data(contentsOf: url), let image = UIImage(data: data) else { return }
view.backgroundColor = UIColor(white: 0, alpha: 1)
imageView.image = image
}
@IBAction func startSavingImage(_ sender: AnyObject) {
saveButton.isEnabled = false
filterButton.isEnabled = false
activityIndicator("Saving Image")
DispatchQueue.main.async {
self.saveImage()
DispatchQueue.main.async {
self.effectView.removeFromSuperview()
self.saveButton.isEnabled = true
self.filterButton.isEnabled = true
}
}
}
@IBAction func filterAction(_ sender: AnyObject) {
filterButton.isEnabled = false
saveButton.isEnabled = false
activityIndicator("Applying Filter")
DispatchQueue.main.async {
self.applyFilterToImage()
DispatchQueue.main.async {
self.effectView.removeFromSuperview()
self.filterButton.isEnabled = true
self.saveButton.isEnabled = true
}
}
}
@IBAction func cameraAction(_ sender: AnyObject) {
if UIImagePickerController.isSourceTypeAvailable(.camera) {
imagePicker.delegate = self
imagePicker.sourceType = .camera
present(imagePicker, animated: true)
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [AnyHashable: Any]!) {
dismiss(animated: true, completion: nil)
imageView.image = image
}
}


extension Data {
var image: UIImage? { return UIImage(data: self) }
}


extension UIImage {
var data: Data? { return UIImagePNGRepresentation(self) }
func applying(contrast value: NSNumber) -> UIImage? {
guard let ciImage = CIImage(image: self)?.applyingFilter("CIColorControls", withInputParameters: [kCIInputContrastKey: value]) else { return nil }
UIGraphicsBeginImageContextWithOptions(size, false, scale)
defer { UIGraphicsEndImageContext() }
UIImage(ciImage: ciImage).draw(in: CGRect(origin: .zero, size: size))
return UIGraphicsGetImageFromCurrentImageContext()
}
}


How can i use activity indicator when a user registers or login messageView using swift 3

To show activity indicator, first declare it at class level and then initialize it.

 var activityIndicator:UIActivityIndicatorView!

Then in your viewdidLoad() method, initialize activityIndicator.

 activityIndicator =  UIActivityIndicatorView(activityIndicatorStyle: .gray)
activityIndicator.center = view.center
activityIndicator.isHidden = true
self.view.addSubview(activityIndicator)

You can write two methods to start and stop activity indicator in your view controller as:

  func displayActivityIndicatorView() -> () {
UIApplication.shared.beginIgnoringInteractionEvents()
self.view.bringSubview(toFront: self.activityIndicator)
self.activityIndicator.isHidden = false
self.activityIndicator.startAnimating()
}

func hideActivityIndicatorView() -> () {
if !self.activityIndicator.isHidden{
DispatchQueue.main.async {
UIApplication.shared.endIgnoringInteractionEvents()
self.activityIndicator.stopAnimating()
self.activityIndicator.isHidden = true

}
}

}

Now start activity indicator just after validating the login data and before hitting the login API as:

 func handleLogin() {
guard let email = emailTextField.text, let password = passwordTextField.text else {
print("Form is not valid")
return
}
//start activity indicator
self. displayActivityIndicatorView()
FIRAuth.auth()?.signIn(withEmail: email, password: password, completion: { (user, error) in

if error != nil {
print(error ?? "")
//stop activity indicator
self. hideActivityIndicatorView()
return
}

//successfully logged in our user
//stop activity indicator
self. hideActivityIndicatorView()
self.messagesController?.fetchUserAndSetupNavBarTitle()

self.dismiss(animated: true, completion: nil)

})

}

How do I place my activityIndicator programmatically?

Basically, you can do this in just a few lines of code:

 func showActivityIndicatory() {
let activityView = UIActivityIndicatorView(style: .whiteLarge)
activityView.center = self.view.center
self.view.addSubview(activityView)
activityView.startAnimating()
}

If you need more controll on activityView please set Origin of container view to place activityindicator anywhere on the screen.

func showActivityIndicatory() {
let container: UIView = UIView()
container.frame = CGRect(x: 0, y: 0, width: 80, height: 80) // Set X and Y whatever you want
container.backgroundColor = .clear

let activityView = UIActivityIndicatorView(style: .whiteLarge)
activityView.center = self.view.center

container.addSubview(activityView)
self.view.addSubview(container)
activityView.startAnimating()
}

How to display activity indicator in center of UIAlertController?

Be sure to set the frame property when you're creating a view.

func displaySignUpPendingAlert() -> UIAlertController {
//create an alert controller
let pending = UIAlertController(title: "Creating New User", message: nil, preferredStyle: .Alert)

//create an activity indicator
let indicator = UIActivityIndicatorView(frame: pending.view.bounds)
indicator.autoresizingMask = [.flexibleWidth, .flexibleHeight]

//add the activity indicator as a subview of the alert controller's view
pending.view.addSubview(indicator)
indicator.isUserInteractionEnabled = false // required otherwise if there buttons in the UIAlertController you will not be able to press them
indicator.startAnimating()

self.presentViewController(pending, animated: true, completion: nil)

return pending
}

To @62Shark:

let pending = UIAlertController(title: "Creating New User", message: nil, preferredStyle: .Alert)

let indicator = UIActivityIndicatorView()
indicator.setTranslatesAutoresizingMaskIntoConstraints(false)
pending.view.addSubview(indicator)

let views = ["pending" : pending.view, "indicator" : indicator]
var constraints = NSLayoutConstraint.constraintsWithVisualFormat("V:[indicator]-(-50)-|", options: nil, metrics: nil, views: views)
constraints += NSLayoutConstraint.constraintsWithVisualFormat("H:|[indicator]|", options: nil, metrics: nil, views: views)
pending.view.addConstraints(constraints)

indicator.userInteractionEnabled = false
indicator.startAnimating()

self.presentViewController(pending, animated: true, completion: nil)

Display activity indicator while fetching api data

As you can show any view in body add a boolean @State variable with initial value true and show a ProgressView. After loading the data set the variable to false which shows the Picker.

Move the .onAppear modifier to after Form.

var body: some View {
@State private var isLoading = true
// @State private var tipoDenunciaSelecionada ...

NavigationView {
Form {
Section(header: Text("Pesquisar Denúncia")) {
//some code...
if isLoading {
HStack(spacing: 15) {
ProgressView()
Text("Loading…")
}
} else {
Picker(selection: $tipoDenunciaSelecionada, label: Text("Tipo de Denúncia")) {
ForEach(tiposDenuncia, id: \.self) {item in
Text(item.nome ?? "")
}
}

//some more code...
}.onAppear(perform: carregarTipoDenuncia)
}
}
}


let response = try decoder.decode([TipoDenunciaModel].self, from: data)
DispatchQueue.main.async {
self.tiposDenuncia = response
self.isLoading = false
}
...


Related Topics



Leave a reply



Submit