Is there any way to show error msg to user from worker thread in IOS from Appdelegate before root view controller is instantiated/created?

61 views Asked by At

I want to show user a alert in case my application stop before creating a window to show root view controller and i want to do this from a worker thread which will be running in a cpp file and will be calling swift file before a UIApplication.shared.delegate is created.So , I want to show a error message to user from worker thread without switching to main thread (without using DispactchQueue.main.sync{code...})

I tried a using a UIAlertController to present it from worker thread but xcode yelled at me to use it to call from main thread.Is there way to show error message to user to let him know to update/make changes in his system before start app??

.swift file

import UIKit

@objc class AlertPopUpInWin:NSObject{
    @objc func AlertPopUp(labelText:NSString){
        print(labelText)
        let delegate = UIApplication.shared.delegate
        let window = delegate?.window
        let vc = window?!.rootViewController as! ViewController
        let alert = UIAlertController(title: "hello", message: labelText as String, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default))
        vc.present(alert, animated: true)
        
    }
}

.cpp file - to call AlertPopUP() function from cpp

#include "AlertPopUpDailog.hpp"
#include <iostream>
#include "SwiftWrapper.h"
#include "thread"
#include <cstdlib>
using namespace std;

void AlertPopUpDailog::UpdateAlertDailogInWorkerThread()
{
    std::thread t1(AlertPopUpDailog::SwiftFuncCaller);

    t1.detach();
    
}


void AlertPopUpDailog::SwiftFuncCaller()
{
    char* alertText = "Alert - hello";
    SwiftWrapper::AlertPopUpSwiftWrapper(alertText);
}

1

There are 1 answers

2
Caleb On

I tried a using a UIAlertController to present it from worker thread but xcode yelled at me to use it to call from main thread.Is there some other artefact which is thread safe

As a rule, anything that touches the UI has to run on the main thread. So the direct answer to your question is no, there's no other way to go about it.

That said, there shouldn't be any reason that you can't use the main thread. If you've got a worker thread that's deciding whether to show the alert, that's fine; when it has made it's decision, it just needs to signal the main thread to show the alert (or not). It sounds like you might be blocking the main thread waiting for the decision to be made? If so, don't do that. Just defer whatever you're doing on the main thread that should be deferred until after the decision comes down.