Why do my async calls still block me from interacting with UI elements in Swift? - objective-c

My scenerio:
I asynchronously call a downloader object function to try to download a file.
Within the downloader's function, it asynchronously initiates a connection for downloading.
Even so, I cannot interact with my UI elements.
For example, I cannot edit my text field while download is in progress.
I want to be able to interact with my UI elements while downloading.
Where did I miss? What should I do? I truly appreciate your help!
ViewController's snippet for async download
//relevant UI elements I am referring to
#IBOutlet var renderButton: UIButton!
#IBOutlet var urlField: UITextField!
func handleOpenURL(url: NSURL){
var downloader: aDownloader = aDownloader(url: url)
//I try to put download to background thread
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), {() -> Void in
//This function initiates a connection call in an attempt to download the file
downloader.executeConnection({
(dataURL:NSURL!,error:NSError!) -> Void in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.imageView.image = UIImage(data:NSData(contentsOfURL: url)!)
})
//rest are nonsense
}, progress: { (percentage:Double) -> Void in
//nonsense
}
)
})
}
aDownloader.swift 's snippet for relevant code
class aDownloader: NSObject, allOtherProtocols {
unowned var url: NSURL
//this block reports the progress as a % number
var progressBlock : ((Double)->Void)?
//this block will return either the destinationFileURL after download finishes,
//or return error of any sort
var dataBlock: ((NSURL!,NSError!)->Void)?
init(url: NSURL) {
self.url = url
}
func executeConnection(received:(NSURL!,NSError!)->Void, progress:(Double)->Void){
var request : NSURLRequest = NSURLRequest(URL: self.url,
cachePolicy: .ReloadIgnoringLocalCacheData,
timeoutInterval: 60.0)
//I attempt to async-ly download the file here
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), { () -> Void in
var connectionManager : NSURLConnection? = NSURLConnection(request:request,
delegate: self,
startImmediately: false)
connectionManager?.scheduleInRunLoop(NSRunLoop.mainRunLoop(),
forMode: NSRunLoopCommonModes)
connectionManager?.start()
})
self.dataBlock = received
self.progressBlock = progress
}
//nonsense
}

Two things.
Most importantly, you are still configuring your configuration manager to run on the main loop:
connectionManager?.scheduleInRunLoop(NSRunLoop.mainRunLoop(),
forMode: NSRunLoopCommonModes)
You will probably find it easier to just use NSURLConnection's class method
sendAsynchronousRequest:queue:completionHandler: instead of manually starting the request in a background thread.
Also, it is a bad idea to update UI elements from a background thread:
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.imageView.image = UIImage(data:NSData(contentsOfURL: url)!)
})
Instead, you should load the image into a temporary variable in the background and then perform the actual assignment back on the main thread.

Related

How does a view obtain data using a view model and Network API

I'm trying to fetch some data with this helper file:
https://gist.github.com/jbfbell/e011c5e4c3869584723d79927b7c4b68
Here's a snippet of the important code:
Class
/// Base class for requests to the Alpha Vantage Stock Data API. Intended to be subclasssed, but can
/// be used directly if library does not support a new api.
class AlphaVantageRequest : ApiRequest {
private static let alphaApi = AlphaVantageRestApi()
let method = "GET"
let path = ""
let queryStringParameters : Array<URLQueryItem>
let api : RestApi = AlphaVantageRequest.alphaApi
var responseJSON : [String : Any]? {
didSet {
if let results = responseJSON {
print(results)
}
}
}
}
Extension ApiRequest
/// Makes asynchronous call to fetch response from server, stores response on self
///
/// - Returns: self to allow for chained method calls
public func callApi() -> ApiRequest {
guard let apiRequest = createRequest() else {
print("No Request to make")
return self
}
let session = URLSession(configuration: URLSessionConfiguration.ephemeral)
let dataTask = session.dataTask(with: apiRequest) {(data, response, error) in
guard error == nil else {
print("Error Reaching API, \(String(describing: apiRequest.url))")
return
}
self.receiveResponse(data)
}
dataTask.resume()
return self
}
My goal is to fetch the data from responseJSON after the data of the url request is loaded.
My ViewModel currently looks like this:
class CompanyViewModel: ObservableObject {
var companyOverviewRequest: ApiRequest? {
didSet {
if let response = companyOverviewRequest?.responseJSON {
print(response)
}
}
}
private var searchEndpoint: SearchEndpoint
init(companyOverviewRequest: AlphaVantageRequest? = nil,
searchEndpoint: SearchEndpoint) {
self.companyOverviewRequest = CompanyOverviewRequest(symbol: searchEndpoint.symbol)
}
func fetchCompanyOverview() {
guard let request = self.companyOverviewRequest?.callApi() else { return }
self.companyOverviewRequest = request
}
}
So in my ViewModel the didSet gets called once but not when it should store the data. The results of AlphaVantageRequest always prints out properly, but not in my ViewModel. How can I achieve to have the loaded data also in my ViewModel?
When you use a view model which is an ObservableObject, your view wants to observe published properties, usually a viewState (MVVM terminology):
class CompanyViewModel: ObservableObject {
enum ViewState {
case undefined
case value(Company)
}
#Published var viewState: ViewState = .undefined
viewState completely describes how your view will be rendered. Note, that it can be undefined - which your view should be able to handle.
Adding a loading(Company?) case would also be a good idea. Your view can then render a loading indicator. Note that loading also provides an optional company value. You can then render a "refresh", in which case you already have a company value while also drawing a loading indicator.
In order to fetch some data from an endpoint, you may use the following abstraction:
public protocol HTTPClient: class {
func publisher(for request: URLRequest) -> AnyPublisher<HTTPResponse, Swift.Error>
}
This can be implemented by a simple wrapper around URLSession with 5 lines of code. A conforming type may however do much more: it may handle authentication, authorization, it may retry requests, refresh access tokens, or present user interfaces where the user needs to authenticate, etc. This simple protocol is sufficient for all this.
So, how does your ViewModel get the data?
It makes sense to introduce another abstraction: "UseCase" which performs this task, and not let the view model directly use the HTTP client.
A "use case" is simply an object that performs a task, taking an input and producing an output or error. You can name it how you want, "DataProvider", "ContentProvider" or something like this. "Use Case" is a well known term, though.
Conceptually, it has a similar API as an HTTP client, but semantically it sits on a higher level:
public protocol UseCase {
associatedtype Input: Encodable
associatedtype Output: Decodable
associatedtype Error
func callAsFunction(with input: Input) -> AnyPublisher<Output, Error>
}
Lets create us a "GetCompany" use case:
struct Company: Codable {
var name: String
var id: Int
}
struct GetCompanyUseCase: UseCase {
typealias Input = Int
typealias Output = Company
typealias Error = Swift.Error
private let httpClient: HTTPClient
init(httpClient: HTTPClient) {
self.httpClient = httpClient
}
func callAsFunction(with id: Int) -> AnyPublisher<Company, Swift.Error> {
let request = composeURLRequest(input: id)
return httpClient.publisher(for: request)
.tryMap { httpResponse in
switch httpResponse {
case .success(_, let data):
return data
default:
throw "invalid status code"
}
}
.decode(type: Company.self, decoder: JSONDecoder())
.map { $0 } // no-op, usually you receive a "DTO.Company" value and transform it into your Company type.
.eraseToAnyPublisher()
}
private func composeURLRequest(input: Int) -> URLRequest {
let url = URL(string: "https://api.my.com/companies?id=\(input)")!
return URLRequest(url: url)
}
}
So, this Use Case clearly accesses our HTTP client. We can implement this accessing CoreData, or read from file, or using a mock, etc. The API is always the same, and the view model does not care. The beauty here is, you can switch it out and swap in another one, the view model still works and also your view. (In order to make this really cool, you would create a AnyUseCase generic type, which is very easy, and here you have your dependency injection).
Now lets see how the view model may look like and how it uses the Use Case:
class CompanyViewModel: ObservableObject {
enum ViewState {
case undefined
case value(Company)
}
#Published var viewState: ViewState = .undefined
let getCompany: GetCompanyUseCase
var getCompanyCancellable: AnyCancellable?
init(getCompany: GetCompanyUseCase) {
self.getCompany = getCompany
}
func load() {
self.getCompanyCancellable =
self.getCompany(with: 1)
.sink { (completion) in
print(completion)
} receiveValue: { (company) in
self.viewState = .value(company)
print("company set to: \(company)")
}
}
}
The load function triggers the use case, which calls the underlying http client to load the company data.
When the UseCase returns a company, it will be assigned the view state. Observers (the view, or ViewController) will get notified about the change and can preform an update.
You can experiment with code in playground. Here are the missing peaces:
import Foundation
import Combine
extension String: Swift.Error {}
public enum HTTPResponse {
case information(response: HTTPURLResponse, data: Data)
case success(response: HTTPURLResponse, data: Data)
case redirect(response: HTTPURLResponse, data: Data)
case clientError(response: HTTPURLResponse, data: Data)
case serverError(response: HTTPURLResponse, data: Data)
case custom(response: HTTPURLResponse, data: Data)
}
class MockHTTPClient: HTTPClient {
func publisher(for request: URLRequest) -> AnyPublisher<HTTPResponse, Swift.Error> {
let json = #"{"id": 1, "name": "Some Corporation"}"#.data(using: .utf8)!
let url = URL(string: "https://api.my.com/companies")!
let httpUrlResponse = HTTPURLResponse(url: url, statusCode: 200, httpVersion: nil, headerFields: nil)!
let response: HTTPResponse = .success(response: httpUrlResponse, data: json)
return Just(response)
.mapError { _ in "no error" }
.eraseToAnyPublisher()
}
}
Assemble:
let httpClient = MockHTTPClient()
let getCompany = GetCompany(httpClient: httpClient)
let viewModel = CompanyViewModel(getCompany: getCompany)
viewModel.load()

iOS Box API - wait for request to finish

Is there a way to wait for the Box API to finish all requests? So for example, if I make a folder item request, I would like to have my program wait for the completion handler to finish before moving on.
As an example:
BOXContentClient *contentClient = [BOXContentClient defaultClient];
BOXFolderItemsRequest *listAllInRoot = [contentClient folderItemsRequestWithID:BOXAPIFolderIDRoot];
[listAllInRoot performRequestWithCompletion:^(NSArray *items, NSError *error) {
//Do something with the results here
}
// Wait here for the completion handler to finish before moving on
I had a go at using an NSCondition, however I am wondering if there's a better way.
(Swift 5.x) You can use this code :
var a: [String:Any]
func myFunction(completion:#escaping (Bool) -> () ) {
DispatchQueue.main.async {
// For example your action on a
}
}
myFunction { (status) in
if status {
print(a!)
}
}

Swift Here API Examples

I'm incorporating the HERE SDK into my app. Aside from one simple map setup, all the examples on the HERE website are shown in objective-C, and I'm trying my best to translate them into Swift but it's not working 100% yet. I'm trying to put a route between 2 coordinates onto a map view as per their routing example shown at:
https://developer.here.com/mobile-sdks/documentation/ios/topics/routing.html
The interesting thing is that if I just call for the map everything works, but if I add the routing part I get the following error:
NMAKit FATAL: License Key, App ID, or App Code not set. error on launch which is odd because the credentials are fine! So I think the bug is entirely in my Swift translation.
The instructions in objective-C are very clear:
1. Adopt NMARouteManagerDelegate protocol and create a NMARouteManager:
#interface ClassName : NSObject <NMARouteManagerDelegate>
{
// Setup your class
}
(void)setup
{
Create a NMARouteManager.**
NMARouteManager* routeManager = [NMARouteManager sharedRouteManager];
// Setup delegate
[routeManager setDelegate:self];
}
2. Create an NSMutableArray and add two NMAGeoCoordinates stops:
NSMutableArray* stops = [[NSMutableArray alloc] initWithCapacity:4];
NMAGeoCoordinates* geoCoord1 = [[NMAGeoCoordinates alloc]
initWithLatitude:49.1966286 longitude:-123.0053635];
NMAGeoCoordinates* geoCoord2 = [[NMAGeoCoordinates alloc]
initWithLatitude:49.1947289 longitude:-123.1762924];
[stops addObject:geoCoord1];
[stops addObject:geoCoord2];
3. Create an NMARoutingMode and set its NMATransportMode, NMARoutingType and NMARoutingOption values:
NMARoutingMode* routingMode = [[NMARoutingMode alloc]
initWithRoutingType:NMARoutingTypeFastest
transportMode:NMATransportModeCar
routingOptions:0];
4. Calculate the route:
[routeManager calculateRouteWithStops:stops routingMode:routingMode];
5. To receive the results of the route calculation, implement the NMARouteManagerDelegate protocol method
routeManager:didCalculateRoutes:withError:violatedOptions: in your delegate class.
Note: Routes are returned even if you receive the NMARouteManagerErrorViolatesOptions error. It is up to you to handle these route results that violate routing options.
-(void) routeManager: (NMARouteManager*)routeManager
didCalculateRoutes:(NSArray*)routes
withError:(NMARouteManagerError)error
violatedOptions:(NSArray*)violatedOptions
{
// If the route was calculated successfully
if (!error && routes && routes.count > 0)
{
NMARoute* route = [routes objectAtIndex:0];
// Render the route on the map
mapRoute = [NMAMapRoute mapRouteWithRoute:route];
[mapView addMapObject:mapRoute];
}
else if (error)
{
// Display a message indicating route calculation failure
}
}
And this is what I'm trying to do in Swift:
import UIKit
//I changed the NMARouteManagerDelegate to my original class here
//and couldnt allow NSObject in the class delegation because it conflicts with UIViewController
class TestViewController: UIViewController, NMARouteManagerDelegate {
var mapCircle:NMAMapCircle?
#IBOutlet weak var mapView: NMAMapView!
#IBAction func get_route_action(sender: AnyObject) {
doRouting()
}
let routeManager = NMARouteManager.sharedRouteManager()
func doRouting() {
let geoCoord1 = NMAGeoCoordinates(latitude:41.350949, longitude:-74.182097)
let geoCoord2 = NMAGeoCoordinates(latitude:41.3437502, longitude:-74.1624284)
let stops = [geoCoord1, geoCoord2]
routeManager.calculateRouteWithStops(stops)
}
func routeManager(routeManager: NMARouteManager!, didCalculateRoutes routes: [AnyObject]!, withError error: NMARouteManagerError, violatedOptions: [AnyObject]!) {
print(routes)
print(error)
print(violatedOptions)
guard error == NMARouteManagerError.None else {
print("Route calculation error: \(error)")
return
}
guard let routes = routes, route = routes[0] as? NMARoute else {
print("Route calculation error: no routes")
return
}
let mapRoute = NMAMapRoute(route: route)
// Render the route on the map
mapView.addMapObject(mapRoute)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
//mapView.useHighResolutionMap = true
var coordinates: NMAGeoCoordinates
coordinates = NMAGeoCoordinates(latitude: 41.350949, longitude: -74.182097)
mapView.zoomLevel = 13.2
mapView.setGeoCenter(coordinates, withAnimation: NMAMapAnimation.Linear)
mapView.copyrightLogoPosition = NMALayoutPosition.BottomCenter
addMapCircle()
}
func addMapCircle() {
if mapCircle == nil {
let coordinates: NMAGeoCoordinates =
NMAGeoCoordinates(latitude: 41.350949, longitude: -74.182097)
mapCircle = NMAMapCircle(geoCoordinates: coordinates, radius: 50)
mapView.addMapObject(mapCircle)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
I tried your code, and worked basically for me quite fine.
But I additionally added the credentials in AppDelegate.swift:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
NMAApplicationContext.setAppId(YourAppID, appCode: YourToken, licenseKey: YourKey);
return true;
}
This is critical, since if it's missing, it's throwing exactly the error you get.

CoreData app takes too long to quit

My app may create / delete thousands of managed objects while running. I have used secondary NSManagedObjectContexts(MOCs) with NSPrivateQueueConcurrencyType and NSOperations to make the app more responsive and most parts work well. But when I pressed ⌘Q and if the number of unsaved objects are large, the app hangs for quite a while before the window closes (the beach ball keeps on rotating...).
How to make the window disappear immediately, before the save of the MOC?
I tried to insert window.close() in applicationShouldTerminate in the AppDelegate, but it has no effect.
My code for deletion is nothing special, except the hierachy is really large. Something like
let items = self.items as! Set<Item>
Group.removeItems(items)
for i in items {
self.managedObjectContext?.deleteObject(i)
}
Item is a hierarchic entity. Group has a one-to-many relationship to items.
The removeItems is generated by CoreData with #NSManaged.
Many thanks.
Updates
I tried the following code, the save still blocks the UI.
#IBAction func quit(sender: AnyObject) {
NSRunningApplication.currentApplication().hide()
NSApp.terminate(sender)
}
func applicationShouldTerminate(sender: NSApplication) -> NSApplicationTerminateReply
{
let op = NSBlockOperation { () -> Void in
do {
try self.managedObjectContext.save()
} catch {
print("error")
}
NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
NSApp.replyToApplicationShouldTerminate(true)
})
}
op.start()
return .TerminateLater
}
This doesn't make the window close first, when the amount of created / deleted managed objects is large.
Then I changed to the following, as suggested by #bteapot. Still has no effect. The window still won't close immediately.
#IBAction func quit(sender: AnyObject) {
NSRunningApplication.currentApplication().hide()
NSApp.terminate(sender)
}
func applicationShouldTerminate(sender: NSApplication) -> NSApplicationTerminateReply {
let op = NSBlockOperation { () -> Void in
self.managedObjectContext.performBlock({ () -> Void in
do {
try self.managedObjectContext.save()
} catch {
print("errr")
}
})
NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
NSApp.replyToApplicationShouldTerminate(true)
})
}
dispatch_async ( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
{() -> Void in
op.start()
})
return .TerminateLater
}
Finally I sort of solved the problem, though the UI is still blocked sometimes, even with the same test data.
The approach used can be found here: https://blog.codecentric.de/en/2014/11/concurrency-coredata/ , Core Data background context best practice , https://www.cocoanetics.com/2012/07/multi-context-coredata/
First I made a backgroundMOC with .PrivateQueueConcurrencyType
lazy var backgroundMOC : NSManagedObjectContext = {
let coordinator = self.persistentStoreCoordinator
let moc = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
moc.persistentStoreCoordinator = coordinator
moc.undoManager = nil
return moc
}()
Then made it prent of the original moc.
lazy var managedObjectContext: NSManagedObjectContext = {
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
// managedObjectContext.persistentStoreCoordinator = coordinator
managedObjectContext.parentContext = self.backgroundMOC
managedObjectContext.undoManager = nil
return managedObjectContext
}()
Two methods for the save.
func saveBackgroundMOC() {
self.backgroundMOC.performBlock { () -> Void in
do {
try self.backgroundMOC.save()
NSApp.replyToApplicationShouldTerminate(true)
} catch {
print("save error: bg")
}
}
}
func saveMainMOC() {
self.managedObjectContext.performBlock { () -> Void in
do {
try self.managedObjectContext.save()
self.saveBackgroundMOC()
} catch {
print("save error")
}
}
}
Change the applicationShouldTerminate() to
func applicationShouldTerminate(sender: NSApplication) -> NSApplicationTerminateReply {
if !managedObjectContext.commitEditing() {
NSLog("\(NSStringFromClass(self.dynamicType)) unable to commit editing to terminate")
return .TerminateCancel
}
if !managedObjectContext.hasChanges {
return .TerminateNow
}
saveMainMOC()
return .TerminateLater
}
The reason it was so slow was I was using NSXMLStoreType instead of NSSQLiteStoreType.
Quitting an application might take a while since it will first empty the processes in queue.
Do you want immediate quit discarding everything in the Parent or children MOCs? But this will result in data loss.
If you have multi window application then, then close the window only but not quit the app.
Also thousands of entry should not take longer than 5 seconds to get processed and saved, if you have managed it properly. There could be some loopholes in your code, try to optimize using Instruments, CoreData profiler tool that would help you to understand the amount of time it is eating up.
To hide the window you can use the below, and in background all the coredata processing will happen, and once everything is done the app will terminate.
[self.window orderOut:nil];

How to run WebView.mainFrame.loadRequest synchronously?

In my app I'm trying to navigate to a given URL using a WebView (non visible). However, loading web content happens asynchronously. For later processing I need this however to wait until all web content is loaded (including redirections).
I experimented with CFRunLoopRunInMode to make it wait (or timeout) but cannot get it to work properly with the available loop modes. With kCFRunLoopDefaultMode no redirection is done and the load request stops with the first address. The mode kCFRunLoopCommonModes even crashs after the load request (swift code, so I don't have any useful error information).
I have registered my class as frame load delegate so I know when everything is loaded (even after multiple redirections). I just need make it work while a run loop is active (it works nicely without). Code:
override func webView(sender: WebView!, didStartProvisionalLoadForFrame frame: WebFrame!) {
jsLogger.logInfo("==> Start loading");
}
override func webView(sender: WebView!, willPerformClientRedirectToURL URL: NSURL!,
delay seconds: NSTimeInterval, fireDate date: NSDate!, forFrame frame: WebFrame!) {
redirecting = true;
}
override func webView(sender: WebView!, didCreateJavaScriptContext context: JSContext, forFrame: WebFrame!) {
jsLogger.logInfo("==> JS create");
}
override func webView(sender: WebView!, didFinishLoadForFrame frame: WebFrame!) {
if redirecting {
redirecting = false;
return;
}
jsLogger.logInfo("==> Navigating to: " + sender.mainFrameURL);
}
override func webView(sender: WebView!, didFailLoadWithError error: NSError!, forFrame frame: WebFrame!) {
jsLogger.logError("Navigating to webpage failed with error \(error.localizedDescription)")
}
And here the code to load a URL with the runloop:
func navigateAndWait(location: String) -> String {
if let url = NSURL(string: location) {
redirecting = false;
webClient.mainFrame.loadRequest(NSURLRequest(URL: url));
let result: Int = Int(CFRunLoopRunInMode(kCFRunLoopDefaultMode, 10, Boolean(0)));
switch result {
case kCFRunLoopRunFinished:
return "Invalid run loop";
case kCFRunLoopRunTimedOut:
return "Call timed out";
case kCFRunLoopRunStopped:
fallthrough;
default: // Everything ok.
return "";
}
}
return "Invalid URL";
}
What other ways exist to make my thread wait for the load request to finish?
Note: a solution can be given for both Obj-C and Swift.
You can use performSelector:onThread: in webViewDidFinishLoad: and didFailLoadWithError: to perform any task you want when the webview finishes load.