[英]Multithreading in swift
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). 在上面的代码中,我在
getResponse
函数的辅助线程中设置了self.cred
....这需要时间,因为它是一个服务器调用....主线程中的self.cred
在执行时返回nil早于我们在辅助线程中设置之前...如何返回来自辅助线程的值self.cred
。(不要停止主线程)用户不必经历延迟...但是应该是不返回(应该返回辅助线程中的值)。
There are few ways to implement multi-threading in iOS: 在iOS中实现多线程的方法很少:
Objective C: 目标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: 目标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: 目标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: 另请查看以下链接了解更多详情:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.