在Swift中使用AFNetworking接收响应

时间:2016-01-08 04:48:21

标签: ios iphone json swift afnetworking-2

我是AFNetworking的新手,我正在尝试遵循Raywenderlich的教程。所以我有JSON解析的代码,我正在努力将其转换为Swift。我已经尝试了很多教程和StackOverflow的答案,但无法找到一个好的解释。

- (IBAction)jsonTapped:(id)sender
{
    // 1
    NSString *string = [NSString stringWithFormat:@"%@weather.php?format=json", BaseURLString];
    NSURL *url = [NSURL URLWithString:string];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    // 2
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    operation.responseSerializer = [AFJSONResponseSerializer serializer];

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

        // 3
        self.weather = (NSDictionary *)responseObject;
        self.title = @"JSON Retrieved";
        [self.tableView reloadData];

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        // 4
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather"
                                                            message:[error localizedDescription]
                                                           delegate:nil
                                                  cancelButtonTitle:@"Ok"
                                                  otherButtonTitles:nil];
        [alertView show];
    }];

    // 5
    [operation start];
}

那么,任何人都可以帮助我解决使用AFNetworking解析数据的基础知识吗?

2 个答案:

答案 0 :(得分:2)

问题在于您与.red{ color: red; } .blue{ color: blue; } .green{ color: green; } 中的Objc合作。有许多框架可替代Swift

事实上,同一位开发人员已在名为AlamofireAFNetworking中开发了网络库

您可以使用该框架并获得相同的响应:

以下是它的演示示例!

Swift

答案 1 :(得分:2)

是的,您可以轻松地使用AFnetworking库快速创建Bridging-Header.h文件并将AFNetworking.h导入Bridging-Header.h文件

并在下面的代码中尝试使用json方法

let urlAsString = "<Your json URL in string>"   
        let manager = AFHTTPRequestOperationManager()
        manager.POST(
            urlAsString,
            parameters: <Parameter>,
            success: { (operation: AFHTTPRequestOperation!,
                responseObject: AnyObject!) in
print("JSON: " + responseObject.description)
},
failure: { (operation: AFHTTPRequestOperation!
    error: NSError!) in
  }
 )