Swift中的完成块AFNetworking

时间:2015-09-21 08:35:54

标签: ios swift afnetworking

我正在开发一款iOS应用程序,其基础是带有AFNetworking的Objective-C,用于与API通信。现在我在Swift中编写新的ViewControllers,并在Swift文件中遇到CompletionBlock的问题。

最初的Objective-C代码:

- (void)downloadJson {
    [[ODDWebService sharedInstance] getParkingSpacesWithCompletionBlock:^(NSArray *result, BOOL succes) {
        if(succes) {
            [self.parkings removeAllObjects];

            for(NSDictionary *dict in result) {
                Parking *parking = [[Parking alloc] init];
                parking.name = [dict objectForKey:@"name"];
                parking.freespace = [[dict objectForKey:@"freespace"] integerValue];
                [self.parkings addObject:parking];
            }
            [self updateParkings];
        } else {
            NSLog(@"ERROR RETRIEVING PARKING SPACES");
        }
    }];
}

这就是我认为应该在Swift中的内容:

func downloadJson() {
    ODDWebService.sharedInstance().getParkingSpacesWithCompletionBlock { (result: AnyObject, succes: Bool) -> Void in
        if(succes) {
            self.parkings.removeAllObjects()

            for dict: NSDictionary in result {
                var parking: Parking = Parking
                parking.name = dict["name"]
                parking.freespace = dict["freespace"].integerValue()
                parkings.addObject(parking)
            } else {
                NSLog("ERROR RETRIEVING PARKING SPACES")
            }
        }
    }
}

主要错误见于第二行代码:

'(AnyObject, Bool) -> Void' is not convertible to '(([AnyObject]!, Bool) -> Void)!'

2 个答案:

答案 0 :(得分:0)

您正在尝试将NSArray转换为Anyobject。你能试试这段代码吗?

func downloadJson() {
    ODDWebService.sharedInstance().getParkingSpacesWithCompletionBlock { (result: [AnyObject]!, success: Bool) -> Void in
        if(succes) {
            self.parkings.removeAllObjects()

            for dict in result as NSArray {
                var parking: Parking = Parking
                parking.name = dict["name"]
                parking.freespace = dict["freespace"].integerValue()
                parkings.addObject(parking)
            } else {
                NSLog("ERROR RETRIEVING PARKING SPACES")
            }
        }
    }
}

答案 1 :(得分:0)

替换

in

使用

func downloadJson() {
ODDWebService.sharedInstance().getParkingSpacesWithCompletionBlock { (result: AnyObject, succes: Bool) -> Void in
    if(succes) {

还要将以下代码中的第一行添加到您的代码中。

func downloadJson() {
ODDWebService.sharedInstance().getParkingSpacesWithCompletionBlock {
result, success  in
    if(succes) {