可以将文件:///path/to/local/file/data.json URL与AFHTTPRequestOperation一起使用

时间:2015-01-21 04:55:49

标签: objective-c ios8 afnetworking-2

有没有办法使用AFHTTPRequestOperation来检索本地JSON测试数据文件的内容?以下代码片段的执行遵循失败代码块。我怀疑问题正在发生,因为我正在使用带有file:/// construct的URL。这个假设是否正确?

/** Get JSON from the local file **/

// Create an URL object set to the JSON endpoint.
NSURL *url = [[NSURL alloc] initWithString:@"file:///Users/charlie/Desktop/Xcode%20Projects/Assets/MyProfile.json"];

// Create a URL Load Request using the NSURL.
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];

// Create an AFHTTPRequestOperation to perform the Internet call.
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];


[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id jsonObject) {
    // If the request succeeds:
    NSLog(@"JSON is: %@", jsonObject);
}
                                 failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    // If the request fails:
    NSLog(@"%%ViewController-E-DEBUG, JSON request failed.");
}];

// Start the request operation.
[operation start];

1 个答案:

答案 0 :(得分:0)

您不能将AFNetworking用于本地文件数据,因为AFNetworking用于网络任务,因为这不是网络任务,因此您可以选择该文件并使用NSJsonSerialization在本地解析该文件。 因为假设本地文件在您的项目目录中。

NSString *filePath = [[NSBundle mainBundle] pathForResource:jsonFileName ofType:@"json"];//jsonfilename is the name of your file
NSData *JSONData = [NSData dataWithContentsOfFile:filePath options:NSDataReadingMappedIfSafe error:nil];
NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableContainers error:nil];