如何在成功的JSON响应之后执行更多代码?

时间:2016-09-01 19:33:21

标签: ios swift alamofire

我是swift的初学者,我正在尝试从api中获取一些JSON数据,然后从该Data创建一个数组。

Alamofire.request(.GET, URL)
    .responseJSON
    {
        response in
        let JSON = response.result.value
        let response = JSON as! NSDictionary
        let Data = response.objectForKey("data")!
        for slot in timeSlot as! NSDictionary
        {
            let json = slot.value
            let availability = json as! NSDictionary
            let myavailable = availability.objectForKey("available")!
            let slotTime = availability.objectForKey("time")!
            if (myavailable as! NSNumber == 1)
            {
                self.fetchSlot.append(slotTime as! String)
            }
        }
        for x in self.mySlot
        {
            for c in self.fetchSlot
            {
                if (c == x)
                {
                    self.availableSlot.append(x)
                }
            }
        }
    }

现在我正在尝试打印" self.availableslot"在同一个viewDid加载函数中。 但它总是返回一个空数组,因为它是在获取所有JSON数据之前编译的。

如果有什么办法可以使用重装方法或完成处理程序来完成我的工作。

1 个答案:

答案 0 :(得分:0)

func performAlamoFireRequest(completion: () -> Void) {
    Alamofire.request(.GET, URL).responseJSON {
        response in

        let JSON = response.result.value
        let response = JSON as! NSDictionary
        let Data = response.objectForKey("data")!

        for slot in timeSlot as! NSDictionary {
            let json = slot.value
            let availability = json as! NSDictionary
            let myavailable = availability.objectForKey("available")!
            let slotTime = availability.objectForKey("time")!
            if (myavailable as! NSNumber == 1) {
                self.fetchSlot.append(slotTime as! String)
            }
        }

        for x in self.mySlot {

            for c in self.fetchSlot {
                if (c == x) {
                    self.availableSlot.append(x)
                }
            }
        }
        completion()
    }
}

performAlamoFireRequest() {
//code to perform after here
}