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).
There are few ways to implement multi-threading in iOS:
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()
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. */
})
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With