ios - Swift 中的完成 block AFNetworking

标签 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)!'

最佳答案

替换

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

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

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

if let dicts = result as? NSDictionary<String, AnyObject> {
for dict: NSDictionary in dicts {
            var parking: Parking = Parking
            parking.name = dict["name"]

关于ios - Swift 中的完成 block AFNetworking,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32690703/

相关文章:

ios - 在 IOS 中共享图像/链接到我的应用程序

objective-c - NSTimer 未在子线程中触发

ios - tableviewcell 中的 collectionview 在重用发生时显示错误的数据

ios - AFNetworking 成功/失败 block 是否在主线程上调用?

ios - 如何在 AFNetworking 2.0+ 中使用 AFHTTPRequestOperationManager 使用 cookie?

ios - 将新版本上传到应用商店?

iOS画外音: Focus selected cell and not the first row

swift - SpriteKit - 创建随机对象并使用 deltatime 移动它们

ios - iOS中如何根据不同用户类型动态切换UI主题

ios - 在没有 pod 的情况下导入 AFNetworking