2017-03-01 62 views
0
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 
} 

在上面的代碼我在getResponse功能....副螺紋設置self.cred這需要時間,因爲它是一個服務器呼叫.... self.cred在主線程是返回nil因爲它正在執行的時間早於我們在輔助線程中設置...如何返回來自輔助線程的值self.cred(不要停止主線程)用戶不必經歷延遲...但不應該返回零(應該返回輔助線程中的值)。多線程在迅速

+0

您可能需要使用/的closures__而不是返回一個值__completion塊,有許多在線的例子可以告訴你這個概念的正確方法。 – holex

回答

4

有實現iOS中的多線程幾個方面:

  • NSThread創建一個可以通過調用start方法來啓動一個新的低級別的線程。

目標C:

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

夫特:

var myThread = Thread(target: self, selector: #selector(self.myThreadMainMethod), object: nil) 
myThread.start() 
  • NSOperationQueue允許創建和使用並行執行NSOperations線程池。 NSOperations也可以通過向mainQueue提供NSOperationQueue來在主線程上運行。

目標C:

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

斯威夫特:

var myQueue = NSOperationQueue() 
myQueue.addOperation(anOperation) 
myQueue.addOperationWithBlock({() -> Void in 
    /* Do something. */ 
}) 
  • GCD或大中央調度是Objective-C中的現代功能,它提供了豐富的要使用的方法和API集合普通的多線程任務。 GCD提供了一種在主線程,併發隊列(並行運行任務)或串行隊列(任務按先進先出順序運行)上對任務進行排隊的方法。

目標C:

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

斯威夫特:

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

還詳細信息請參考以下鏈接: