Reputation: 33
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).
Upvotes: 2
Views: 9753
Reputation: 1371
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:
Upvotes: 12