How to indicate network activity in status bar - nsurlsession

I use Alamofire for networking in my iOS application. I need to run this app in iOS 7+. I want to indicate network activity in status bar, so I created this struct:
struct ActivityManager {
static var activitiesCount = 0
static func addActivity() {
if activitiesCount == 0 {
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
}
activitiesCount++
}
static func removeActivity() {
if activitiesCount > 0 {
activitiesCount--
if activitiesCount == 0 {
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
}
}
}
}
But I don't know, where to call in code addActivity() and removeActivity() methods. I don't want to write them with every request. I want to, that they will be called automatically with every request.
I tried also use pure NSURLSession and NSURLSessionTask and extend them:
extension NSURLSessionTask {
func resumeWithActivity() {
ActivityManager.addAction()
self.resume()
}
}
public extension NSURLSession {
func OwnDataTaskWithRequest(request: NSURLRequest!, ownCompletionHandler: ((NSData!, NSURLResponse!, NSError!) -> Void)?) -> NSURLSessionDataTask! {
return self.dataTaskWithRequest(request, completionHandler: { (data, response, error) in
ActivityManager.removeAction()
ownCompletionHandler!(data, response, error)
})
}
}
Then I used them like this:
var session: NSURLSession = NSURLSession(configuration: config, delegate: self, delegateQueue: nil)
session.OwnDataTaskWithRequest(request) { (data, response, error) -> Void in
// some logic here
}.resumeWithActivity()
But this approach doesn't work. In iOS 7 is NSURLSession extension not visible. I created a bug report for this (with sample project).
Can you please give me some advise, how to reach my goal? With or without Alamofire?

If you don't want to call your functions manually for every request and that you want to use Alamofire, I suggest you to improve it to add the network activity indicator feature.
Have a look at the source of Alamofire
You need to register 2 notification observers in your ActivityManager and then trigger the notifications at the relevant places either in Alamofire.Manager or in Alamofire.Request.
Also have a look at the source of AFNetworkActivityIndicatorManager which implement the feature you want in AFNetworking.

Related

Is it possible to use async/await syntax for UIActivityViewController's completionWithItemsHandler property?

I have this function:
struct Downloader {
static func presentDownloader(
in viewController: UIViewController,
with urls: [URL],
_ completion: #escaping (Bool) -> Void
) {
DispatchQueue.main.async {
let activityViewController = UIActivityViewController(
activityItems: urls,
applicationActivities: nil
)
activityViewController.completionWithItemsHandler = { _, result, _, _ in
completion(result)
}
viewController.present(
activityViewController,
animated: true,
completion: nil
)
}
}
}
It simply creates a UIActivityViewController and passes the completionWithItemsHandler as a completion block into the static func.
I am now trying to get rid of all the #escaping/closures as much as I can in order to adopt the new async/await syntax, however I don't know if I can do something here with this.
I started adding an async to my function, and realized that Xcode shows completionWithItemsHandler with an async keyword, but I really have no idea if I can achieve what I want here.
Thank you for your help
Yes, you can do that but you need to write yourself little wrapper over it. So it will look something like that:
#MainActor
func askToShareFile(url: URL) async {
let avc = UIActivityViewController(activityItems: [url], applicationActivities: nil)
present(avc, animated: true)
return await withCheckedContinuation { continuation in
avc.completionWithItemsHandler = { activity, completed, returnedItems, activityError in
print("Activity completed: \(completed), selected action = \(activity), items: \(returnedItems) error: \(activityError)")
if completed {
continuation.resume()
} else {
if activity == nil {
// user cancelled share sheet by closing it
continuation.resume()
}
}
}
}
}
However, important note here that, from my experimentation as of today (iOS 15.5), I can see completion handler is NOT called properly when, on share sheet, user selects any app that handle our file by copying it (activityType = com.apple.UIKit.activity.RemoteOpenInApplication-ByCopy).
If you do some changes - be careful, as you might loose continuation here so please test it yourself too.

is anyone able to restrict the type of the objects dropped on the mac in SwiftUI 3?

as per the documentation, it should be pretty straightforward. example for a List: https://developer.apple.com/documentation/swiftui/list/ondrop(of:istargeted:perform:)-75hvy#
the UTType should be the parameter restricting what a SwiftUI object can receive. in my case i want to accept only Apps. the UTType is .applicationBundle: https://developer.apple.com/documentation/uniformtypeidentifiers/uttype/3551459-applicationbundle
but it doesn't work. the SwiftUI object never changes status and never accepts the drop. the closure is never run. whether on Lists, H/VStacks, Buttons, whatever. the pdf type don't seem to work either, as well as many others. the only type that i'm able to use if fileURL, which is mainly like no restriction.
i'm not sure if i'm doing something wrong or if SwiftUI is half working for the mac.
here's the code:
List(appsToIgnore, id: \.self, selection: $selection) {
Text($0)
}
.onDrop(of: [.applicationBundle, .application], isTargeted: isTargeted) { providers in
print("hehe")
return true
}
replacing or just adding .fileURL in the UTType array makes the drop work but without any type restriction.
i've also tried to use .onInsert on a ForEach instead (https://developer.apple.com/documentation/swiftui/foreach/oninsert(of:perform:)-2whxl#), and to go through a proper DropDelegate (https://developer.apple.com/documentation/swiftui/dropdelegate#) but keep getting the same results. it would seem the SwiftUI drop for macOS is not yet working, but i can't find any official information about this. in the docs it is written macOS 11.0+ so i would expect it to work?
any info appreciated! thanks.
You need to validate manually, using DropDelegate of what kind of file is dragged over.
Here is a simplified demo of possible approach. Tested with Xcode 13 / macOS 11.6
let delegate = MyDelegate()
...
List(appsToIgnore, id: \.self, selection: $selection) {
Text($0)
}
.onDrop(of: [.fileURL], delegate: delegate) // << accept file URLs
and verification part like
class MyDelegate: DropDelegate {
func validateDrop(info: DropInfo) -> Bool {
// find provider with file URL
guard info.hasItemsConforming(to: [.fileURL]) else { return false }
guard let provider = info.itemProviders(for: [.fileURL]).first else { return false }
var result = false
if provider.canLoadObject(ofClass: String.self) {
let group = DispatchGroup()
group.enter() // << make decoding sync
// decode URL from item provider
_ = provider.loadObject(ofClass: String.self) { value, _ in
defer { group.leave() }
guard let fileURL = value, let url = URL(string: fileURL) else { return }
// verify type of content by URL
let flag = try? url.resourceValues(forKeys: [.contentTypeKey]).contentType == .applicationBundle
result = flag ?? false
}
// wait a bit for verification result
_ = group.wait(timeout: .now() + 0.5)
}
return result
}
func performDrop(info: DropInfo) -> Bool {
// handling code is here
return true
}
}

get NSURLSession download progress in all view controllers

So i have a FirstViewController where i download a video with the progress view and progress is working fine using this code
func startDownloading() {
let download = Downloads(url: videoUrl!.absoluteString!)
download.downloadTask = self.downloadsSession.downloadTaskWithURL(videoUrl!)
download.downloadTask!.resume()
download.isDownloading = true
}
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
// 1
print("URLSession Completed for url \(downloadTask.originalRequest?.URL?.absoluteString)")
if let originalURL = downloadTask.originalRequest?.URL?.absoluteString,
destinationURL = localFilePathForUrl(originalURL) {
let fileManager = NSFileManager.defaultManager()
do {
try fileManager.removeItemAtURL(destinationURL)
} catch {
// Non-fatal: file probably doesn't exist
}
do {
try! fileManager.copyItemAtURL(location, toURL: destinationURL)
} catch let error as NSError {
print("Could not copy file to disk: \(error.localizedDescription)")
}
}
}
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
print("URLSession inProgress \(Float(totalBytesWritten)/Float(totalBytesExpectedToWrite))")
if let downloadUrl = downloadTask.originalRequest?.URL?.absoluteString,
let download = activeDownloads[downloadUrl] {
//THIS SETS THE PROGRESS
download.progress = Float(totalBytesWritten)/Float(totalBytesExpectedToWrite)
self.downloadView.state = .Downloading
self.downloadView.setProgress(Double(totalSize)!, animated: true)
}
}
now this code updates FirstViewControllers downloadView.progress correctly but what i want is when i go to SecondViewController i should get the progress of this ongoing download in SecondVC too without starting the download progress again (i know downloading again would be very dumb).
The best way is to separate your network request manager code from the view controller:
Create a separate class to manage the requests, and move your delegate code there.
In the didWriteData method, use NSNotificationCenter to broadcast the notification to any interested view class or make your first view controller notify the second one if it exists.
In each of your view controller classes, register for the notification and when you receive it, update the status accordingly.

Can I mix UIKit and TVMLKit within one app?

I'm exploring tvOS and I found that Apple offers nice set of templates written using TVML. I'd like to know if a tvOS app that utilises TVML templates can also use UIKit.
Can I mix UIKit and TVMLKit within one app?
I found a thread on Apple Developer Forum but it does not fully answer this question and I am going through documentation to find an answer.
Yes, you can. Displaying TVML templates requires you to use an object that controls the JavaScript Context: TVApplicationController.
var appController: TVApplicationController?
This object has a UINavigationController property associated with it. So whenever you see fit, you can call:
let myViewController = UIViewController()
self.appController?.navigationController.pushViewController(myViewController, animated: true)
This allows you to push a Custom UIKit viewcontroller onto the navigation stack. If you want to go back to TVML Templates, just pop the viewController off of the navigation stack.
If what you would like to know is how to communicate between JavaScript and Swift, here is a method that creates a javascript function called pushMyView()
func createPushMyView(){
//allows us to access the javascript context
appController?.evaluateInJavaScriptContext({(evaluation: JSContext) -> Void in
//this is the block that will be called when javascript calls pushMyView()
let pushMyViewBlock : #convention(block) () -> Void = {
() -> Void in
//pushes a UIKit view controller onto the navigation stack
let myViewController = UIViewController()
self.appController?.navigationController.pushViewController(myViewController, animated: true)
}
//this creates a function in the javascript context called "pushMyView".
//calling pushMyView() in javascript will call the block we created above.
evaluation.setObject(unsafeBitCast(pushMyViewBlock, AnyObject.self), forKeyedSubscript: "pushMyView")
}, completion: {(Bool) -> Void in
//done running the script
})
}
Once you call createPushMyView() in Swift, you are free to call pushMyView() in your javascript code and it will push a view controller onto the stack.
SWIFT 4.1 UPDATE
Just a few simple changes to method names and casting:
appController?.evaluate(inJavaScriptContext: {(evaluation: JSContext) -> Void in
and
evaluation.setObject(unsafeBitCast(pushMyViewBlock, to: AnyObject.self), forKeyedSubscript: "pushMyView" as NSString)
As mentioned in the accepted answer, you can call pretty much any Swift function from within the JavaScript context. Note that, as the name implies, setObject:forKeyedSubscript: will also accept objects (if they conform to a protocol that inherits from JSExport) in addition to blocks, allowing you to access methods and properties on that object. Here's an example
import Foundation
import TVMLKit
// Just an example, use sessionStorage/localStorage JS object to actually accomplish something like this
#objc protocol JSBridgeProtocol : JSExport {
func setValue(value: AnyObject?, forKey key: String)
func valueForKey(key: String) -> AnyObject?
}
class JSBridge: NSObject, JSBridgeProtocol {
var storage: Dictionary<String, String> = [:]
override func setValue(value: AnyObject?, forKey key: String) {
storage[key] = String(value)
}
override func valueForKey(key: String) -> AnyObject? {
return storage[key]
}
}
Then in your app controller:
func appController(appController: TVApplicationController, evaluateAppJavaScriptInContext jsContext: JSContext) {
let bridge:JSBridge = JSBridge();
jsContext.setObject(bridge, forKeyedSubscript:"bridge");
}
Then you can do this in your JS: bridge.setValue(['foo', 'bar'], "baz")
Not only that, but you can override views for existing elements, or define custom elements to use in your markup, and back them with native views:
// Call lines like these before you instantiate your TVApplicationController
TVInterfaceFactory.sharedInterfaceFactory().extendedInterfaceCreator = CustomInterfaceFactory()
// optionally register a custom element. You could use this in your markup as <loadingIndicator></loadingIndicator> or <loadingIndicator /> with optional attributes. LoadingIndicatorElement needs to be a TVViewElement subclass, and there are three functions you can optionally override to trigger JS events or DOM updates
TVElementFactory.registerViewElementClass(LoadingIndicatorElement.self, forElementName: "loadingIndicator")
Quick custom element example:
import Foundation
import TVMLKit
class LoadingIndicatorElement: TVViewElement {
override var elementName: String {
return "loadingIndicator"
}
internal override func resetProperty(resettableProperty: TVElementResettableProperty) {
super.resetProperty(resettableProperty)
}
// API's to dispatch events to JavaScript
internal override func dispatchEventOfType(type: TVElementEventType, canBubble: Bool, cancellable isCancellable: Bool, extraInfo: [String : AnyObject]?, completion: ((Bool, Bool) -> Void)?) {
//super.dispatchEventOfType(type, canBubble: canBubble, cancellable: isCancellable, extraInfo: extraInfo, completion: completion)
}
internal override func dispatchEventWithName(eventName: String, canBubble: Bool, cancellable isCancellable: Bool, extraInfo: [String : AnyObject]?, completion: ((Bool, Bool) -> Void)?) {
//...
}
}
And here's how to set up a custom interface factory:
class CustomInterfaceFactory: TVInterfaceFactory {
let kCustomViewTag = 97142 // unlikely to collide
override func viewForElement(element: TVViewElement, existingView: UIView?) -> UIView? {
if (element.elementName == "title") {
if (existingView != nil) {
return existingView
}
let textElement = (element as! TVTextElement)
if (textElement.attributedText!.length > 0) {
let label = UILabel()
// Configure your label here (this is a good way to set a custom font, for example)...
// You can examine textElement.style or textElement.textStyle to get the element's style properties
label.backgroundColor = UIColor.redColor()
let existingText = NSMutableAttributedString(attributedString: textElement.attributedText!)
label.text = existingText.string
return label
}
} else if element.elementName == "loadingIndicator" {
if (existingView != nil && existingView!.tag == kCustomViewTag) {
return existingView
}
let view = UIImageView(image: UIImage(named: "loading.png"))
return view // Simple example. You could easily use your own UIView subclass
}
return nil // Don't call super, return nil when you don't want to override anything...
}
// Use either this or viewForElement for a given element, not both
override func viewControllerForElement(element: TVViewElement, existingViewController: UIViewController?) -> UIViewController? {
if (element.elementName == "whatever") {
let whateverStoryboard = UIStoryboard(name: "Whatever", bundle: nil)
let viewController = whateverStoryboard.instantiateInitialViewController()
return viewController
}
return nil
}
// Use this to return a valid asset URL for resource:// links for badge/img src (not necessary if the referenced file is included in your bundle)
// I believe you could use this to cache online resources (by replacing resource:// with http(s):// if a corresponding file doesn't exist (then starting an async download/save of the resource before returning the modified URL). Just return a file url for the version on disk if you've already cached it.
override func URLForResource(resourceName: String) -> NSURL? {
return nil
}
}
Unfortunately, view/viewControllerForElement: will not be called for all elements. Some of the existing elements (like collection views) will handle the rendering of their child elements themselves, without involving your interface factory, which means you'll have to override a higher level element, or maybe use a category/swizzling or UIAppearance to get the effect you want.
Finally, as I just implied, you can use UIAppearance to change the way certain built-in views look. Here's the easiest way to change the appearance of your TVML app's tab bar, for example:
// in didFinishLaunching...
UITabBar.appearance().backgroundImage = UIImage()
UITabBar.appearance().backgroundColor = UIColor(white: 0.5, alpha: 1.0)
If you already have a native UIKit app for tvOS, but would like to extend it by using TVMLKit for some part of it, You can.
Use the TVMLKit as a sub app in your native tvOS app. The following app shows how to do this, by retaining the TVApplicationController and present the navigationController from the TVApplicationController. The TVApplicationControllerContext is used to transfer data to the JavaScript app, as the url is transferred here :
class ViewController: UIViewController, TVApplicationControllerDelegate {
// Retain the applicationController
var appController:TVApplicationController?
static let tvBaseURL = "http://localhost:9001/"
static let tvBootURL = "\(ViewController.tvBaseURL)/application.js"
#IBAction func buttonPressed(_ sender: UIButton) {
print("button")
// Use TVMLKit to handle interface
// Get the JS context and send it the url to use in the JS app
let hostedContContext = TVApplicationControllerContext()
if let url = URL(string: ViewController.tvBootURL) {
hostedContContext.javaScriptApplicationURL = url
}
// Save an instance to a new Sub application, the controller already knows what window we are running so pass nil
appController = TVApplicationController(context: hostedContContext, window: nil, delegate: self)
// Get the navigationController of the Sub App and present it
let navc = appController!.navigationController
present(navc, animated: true, completion: nil)
}
Yes. See the TVMLKit Framework, whose docs start with:
The TVMLKit framework enables you to incorporate JavaScript and TVML files in your binary apps to create client-server apps.
From a quick skim of those docs, it looks like you use the various TVWhateverFactory classes to create UIKit views or view controllers from TVML, after which you can insert them into a UIKit app.

How to make sure downloaded data is different before assigning it

I have this function that gets a random image from a server, but it seems it does not want to update all the time, I'm thinking it thinks the data has not changed, when it loads a new image on every request. Here is my code, is there any way to make sure (or tell Swift) the data is different before assigning it to the image?
func getNewImage() {
let url = NSURL(string: "http://weboctopi.com/randomcuteimages/rotate.php")!
let task = NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) -> Void in
if error == nil {
self.downloadedImage = UIImage(data: data!)!
self.imagePlaceholder.setImage(self.downloadedImage)
} else {
print(error)
}
}
task.resume()
}
If this is a URL caching problem, you can use a custom configuration for cache busting:
let config = NSURLSessionConfiguration.ephemeralSessionConfiguration()
config.URLCache = nil // don't cache
let task = NSURLSession(configuration: config).dataTaskWithURL(...
I think the reason your image is not updating is because the closure is executed on a background thread and UIKit updates need to be on the main thread. Adding this change to your code should fix the issue:
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.imagePlaceholder?.image = downloadedImage
})

Resources