2016-09-29 253 views
0

在包含另一個函數的函數中調用completionHandler()的正確方法是什麼?基本上,我想在調用completionHandler之前等待嵌入式函數完成。嵌入函數返回值後,在函數中調用completionHandler? Swift

func somefunc {  

transferManager?.download(downloadRequest).continue({(task: AWSTask) -> AnyObject! in 

    // Your handler code here 
    if (task.error != nil) { 
     print("- Error while downloading!") 
     print(task.error) 
    } 

    else if (task.result != nil) { 
     //let downloadOutput: AWSS3TransferManagerDownloadOutput = task.result as! AWSS3TransferManagerDownloadOutput 
     do { 
      let dFile = try NSString(contentsOf: downloadingFileURL as URL, encoding: String.Encoding.utf8.rawValue) 
      print(dFile) 
      modelsParseCSV(contentsOfURL: downloadingFileURL) 
     } 
     catch { 
      print("- Error: Unable to retrieve contents of csv file") 
     } 
    } 
    else { 
     print("- Uknown error: AWSS3 get file") 
    } 


    print("------------ AWS Get Models File End ----------") 
    return nil 

}) 

completionHandler() 
} 
+1

將'completionHandler()'移動到'return nil'上面的行會做訣竅嗎? – dasblinkenlight

+0

更好 - 通過調用'completionHandler()'將調用替換爲'return nil'。但是'completionHandler'在哪裏定義? – rmaddy

+0

對不起,上面定義了缺少代碼完成處理程序,我只是沒有複製它。我看到,如果我在返回nil之前調用completionHandler,則不會調用返回nil。如果我刪除返回語句,它會引發錯誤... –

回答

0

我能解決我自己的問題。下面的代碼調用完成處理函數,並在嵌入函數完成之後:

func AWS_getModelsFile(AWSMake: String, completionHandler: (() -> Void)!) { 

    ......... 

    transferManager?.download(downloadRequest).continue({(task: AWSTask) -> AnyObject! in 

     // Your handler code here 
     if (task.error != nil) { 
      print("- Error while downloading!") 
      print(task.error) 
     } 

     else if (task.result != nil) { 
      //let downloadOutput: AWSS3TransferManagerDownloadOutput = task.result as! AWSS3TransferManagerDownloadOutput 
      do { 
       let dFile = try NSString(contentsOf: downloadingFileURL as URL, encoding: String.Encoding.utf8.rawValue) 
       print(dFile) 
       modelsParseCSV(contentsOfURL: downloadingFileURL) 
      } 
      catch { 
       print("- Error: Unable to retrieve contents of csv file") 
      } 
     } 
     else { 
      print("- Uknown error: AWSS3 get file") 
     } 


     print("------------ AWS Get Models File End ----------") 
     completionHandler() 
     return nil 

    }) 
}