Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multithreading in swift

Tags:

ios

swift

iphone

   func credentials() -> AWSTask<AWSCredentials> {
    var task:AWSTask<AWSCredentials>
    // let task=AWSTask<AWSCredentials>(result:nil)
    print("hello")
    let svc=ServerConnection(action: "m_get_token")
    let req=svc.createRequestWithoutBody("POST")
   let queue=DispatchQueue(label: "credentialsqueue")
    task=AWSTask<AWSCredentials>(result:nil)

    svc.getResponse(req){
        (appresp)->Void in


        print("app response data xx is \(appresp)")
        let k=appresp as? NSDictionary
        let datadict=k!["m_response_data"]! as? NSDictionary

        let kid=datadict?["AccessKeyId"]as?String
        let skid=datadict?["SecretAccessKey"]as?String
        let exp=datadict?["Expiration"]as?String
        let stoken=datadict?["SessionToken"]as?String

        let dateFormatter = DateFormatter()
        dateFormatter.locale = Locale(identifier: "en_US_POSIX")
        dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
        let date = dateFormatter.date(from: exp!)
            DispatchQueue.main.async {
        self.cred=AWSCredentials(accessKey: kid!, secretKey: skid!, sessionKey: stoken!, expiration: date!)     
    }
    print("self.cred is \(self.cred!)")
    task=AWSTask<AWSCredentials>(result:self.cred!)
    return task
}

In the above code i set up self.cred in the secondary thread in the getResponse function....which is taking time as it's a server call....self.cred in the main thread is returning nil as it is being executed early than before we set up in the secondary thread...how to return the value self.cred which is from the secondary thread.(don't stop main thread)User does not have to experience the delay...but nil should not be returned(value in the secondary thread should be returned).

like image 856
Saikrishna Burra Avatar asked May 29 '26 02:05

Saikrishna Burra


1 Answers

There are few ways to implement multi-threading in iOS:

  • NSThread creates a new low-level thread which can be started by calling the start method.

Objective C:

    NSThread* myThread = [[NSThread alloc] initWithTarget:self
    selector:@selector(myThreadMainMethod:)object:nil];
    [myThread start];

Swift:

var myThread = Thread(target: self, selector: #selector(self.myThreadMainMethod), object: nil)
myThread.start()
  • NSOperationQueue allows a pool of threads to be created and used to execute NSOperations in parallel. NSOperations can also be run on the main thread by asking NSOperationQueue for the mainQueue.

Objective C:

    NSOperationQueue* myQueue = [[NSOperationQueue alloc] init];
    [myQueue addOperation:anOperation];
    [myQueue addOperationWithBlock:^{
         /* Do something. */
    }];

Swift:

var myQueue = NSOperationQueue()
myQueue.addOperation(anOperation)
myQueue.addOperationWithBlock({() -> Void in
    /* Do something. */
})
  • GCD or Grand Central Dispatch is a modern feature of Objective-C that provides a rich set of methods and API's to use in order to support common multi-threading tasks. GCD provides a way to queue tasks for dispatch on either the main thread, a concurrent queue (tasks are run in parallel) or a serial queue (tasks are run in FIFO order).

Objective C:

    dispatch_queue_t myQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(myQueue, ^{
       printf("Do some work here.\n");
    });

Swift:

let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)
dispatch_async(queue) {
}

Also Check following links for more details:

  • https://www.raywenderlich.com/148513/grand-central-dispatch-tutorial-swift-3-part-1

  • http://www.appcoda.com/grand-central-dispatch/

like image 146
Sagar Sukode Avatar answered Jun 02 '26 23:06

Sagar Sukode



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!