2015-01-21 59 views
0

有沒有辦法使用AFHTTPRequestOperation檢索本地JSON測試數據文件的內容?以下代碼片段的執行在失敗代碼塊之後。我懷疑問題發生了,因爲我正在使用帶有file:///結構的URL。這個假設是否正確?是否可以使用AFHTTPRequestOperation文件:///path/to/local/file/data.json 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]; 

回答

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];