从关闭swift中获取变量的值

时间:2016-06-30 03:02:00

标签: ios swift http-post closures nsurlsession

所以我有一个名为task的闭包,它是一个post请求,我有一个名为values的全局变量,我试图设置"值"的值。我是从存储在名为" array"的变量中的数据库中检索回来的数据。不要担心tableview.reloadData部分,已经完成了。我只是想知道如何从关闭中获得价值。

    DECLARE @CurrMonth DATE = GETDATE();
    DECLARE @CurrYear NVARCHAR(4) = CAST(YEAR(@CurrMonth) AS NVARCHAR(4))
    DECLARE @END_MM INT = MONTH(@CurrMonth) --Current Month 
    DECLARE @START_MM INT = 1 --Start Month of Current Year

    DECLARE @TB_DATE AS TABLE
    (
        ID INT IDENTITY(1,1),
        DATE_LIST VARCHAR(12)
    )
    WHILE @START_MM <= @END_MM
    BEGIN
        INSERT INTO @TB_DATE (DATE_LIST) VALUES ('['+CONVERT(VARCHAR(3),DATENAME(MONTH, DATEADD(month, @START_MM-1, CAST(@END_MM AS datetime))))+']')
        SET @START_MM=@START_MM+1
    END

    DECLARE @MM_LIST NVARCHAR(MAX) = (SELECT STUFF((SELECT ',' + DATE_LIST 
                        FROM @TB_DATE ORDER BY ID DESC
                        FOR XML PATH('')) ,1,1,'') AS Txt)

    DECLARE @DynamicPivot AS NVARCHAR(MAX)
    SET @DynamicPivot = N'SELECT * FROM (SELECT  
        ItemId,
        ItemName,
        SUM(TotalCost) AS TotalCost, 
        CONVERT(VARCHAR(3), 
        DATENAME(MONTH, DATEADD(MONTH, MONTH(TransDate), - 1))) TransDate
        FROM myTable WHERE YEAR(TransDate) = '+@CurrYear+'
        GROUP BY  TransDate,ItemId,ItemName) AS TP
 PIVOT (SUM(TotalCost) FOR TransDate IN ('+@MM_LIST+')) AS PVTTable';

 EXEC sp_executesql @DynamicPivot

1 个答案:

答案 0 :(得分:3)

对闭包中的任何异步任务使用completion

func get(completion:(value: NSArray) -> Void){

    // request part
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        data, response, error in
        // your serialization code

        dispatch_async(dispatch_get_main_queue()) { [unowned self] in
            self.values = array

            // return value to completion
            completion(value: array)

            print ("error=\(self.values)")
            self.tableView?.reloadData();
        }
    }
} 

更改viewdidload中获取值的方式

   get{(value) in
       // finish NSURLSession task and everything should be done in this closure
        self.values = value
        print ("values=\(self.values)")
    }