4

Normally, in main app, we can use this to show network activity indicator.

[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];

However, in share extension, we don't have [UIApplication sharedApplication]. How can I show network activity indicator in share extension?

Khant Thu Linn
  • 5,905
  • 7
  • 52
  • 120

2 Answers2

2

You just have no access to sharedApplication object from iOS Share Extension, and so cannot use any of the methods on that object.

take a look at part: "Some APIs Are Unavailable to App Extensions"

Use UIActivityIndicatorView instead, you can play with positioning it to status bar even.

0

I'm using this approach for Notification extensions (Service & Content), but in general you have two approaches for APIs that are unavailable in Extensions:

Delegate

Create (or reuse) a protocol that encapsulates the functionality you need. In this case, we just need the activityIndicator flag:

public protocol ActivityIndicatorDelegate {
    var isNetworkActivityIndicatorVisible : Bool { get set }
}

You can have your UIApplicationDelegate implement this protocol, as a pass-through to the UIApplication.shared member.

Then, in your framework, just use the delegate as-needed:

var activityIndicatorDelegate : ActivityIndicatorDelegate? = nil;

// Begin some network activity
self.activityIndicatorDelegate?.isNetworkActivityIndicatorVisible = true;

Function Parameter

If possible, refactor your code to accept a reference to the UIApplication or UIApplicationDelegate object, and then call whatever methods you need directly.

// NOT ALLOWED IN APP EXTENSION
public static var activeTraitCollection : UITraitCollection? {
    let appDelegate = UIApplication.shared.delegate;
    let window = appDelegate?.window;

    return window??.traitCollection;
}

// OK FOR APP EXTENSION
public static func activeTraitCollection (for appDelegate: UIApplicationDelegate) -> UITraitCollection? {
    let window = appDelegate?.window;
    return window??.traitCollection;
}
MandisaW
  • 971
  • 9
  • 21