我需要对URL进行HTTPRequest并解析生成的JSON,我尝试了以下代码
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"viewdidload");
self.responseData = [NSMutableData data];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.gcap.eu/omosanya/download.php"]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(@"didReceiveResponse");
[self.responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@"didFailWithError");
NSLog([NSString stringWithFormat:@"Connection failed: %@", [error description]]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(@"connectionDidFinishLoading");
NSLog(@"Succeeded! Received %lu bytes of data",(unsigned long)[self.responseData length]);
// convert to JSON
NSError *myError = nil;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:_responseData options:NSJSONReadingAllowFragments error:&myError];
// show all values
for(id key in res) {
id value = [res objectForKey:key];
NSString *keyAsString = (NSString *)key;
NSString *valueAsString = (NSString *)value;
NSLog(@"key: %@", keyAsString);
NSLog(@"value: %@", valueAsString);
}
// extract specific value...
NSArray *results = [res objectForKey:@"results"];
for (NSDictionary *result in results) {
NSString *icon = [result objectForKey:@"timestamp"];
NSLog(@"icon: %@", icon);
}
}
我在控制台中收到以下输出:
2015-02-03 17:12:28.201 LSDir[1495:130391] viewdidload
2015-02-03 17:12:28.831 LSDir[1495:130391] didReceiveResponse
2015-02-03 17:12:36.815 LSDir[1495:130391] connectionDidFinishLoading
2015-02-03 17:12:36.815 LSDir[1495:130391] Succeeded! Received 8223702 bytes of data
请注意,没有打印JSON?为什么这样,我该如何解决?我的NSJSONSerialization有什么问题吗?
答案 0 :(得分:0)
请注意json字符串可以是字典或数组。如果你不确定json字符串是哪种,你必须在采取行动之前验证它。这是验证json对象的代码
id jsonObject = [NSJSONSerialization JSONObjectWithData:_responseData options:NSJSONReadingAllowFragments error:&myError];
if ([jsonObject isKindOfClass:[NSArray class]]) {
NSLog(@"its an array!");
NSArray *jsonArray = (NSArray *)jsonObject;
//do your work with this array
}
else {
NSLog(@"its probably a dictionary");
NSDictionary *jsonDictionary = (NSDictionary *)jsonObject;
//do your work with this dictionary
}
答案 1 :(得分:0)
请勿使用NSURLConnection
- 请改用基于块的NSURLSession
API。它是NSURLConnection
的后继者,向后兼容iOS 7。
以下是解决问题所需的代码片段(我认为):
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithURL:[NSURL URLWithString:@"http://www.gcap.eu/omosanya/download.php"]
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error) {
NSError *deserializationError = nil;
if (!error) { // HTTP Reqeust Succeeded
id results = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&deserializationError];
if (!deserializationError) { // Deserialization Succeeded
if ([results isKindOfClass:[NSDictionary class]]) { // Dictionary
NSLog(@"JSON Dictionary Data %@", (NSDictionary *)results);
} else { // Array
NSLog(@"JSON Array Data %@", (NSArray *)results);
}
} else { // Deserialization Failed
NSLog(@"Deserializaiton Error: %@", error);
}
} else { // HTTP Request Failed
NSLog(@"HTTP Error: %@", error);
}}];
[task resume];
NSURLSession
上有一个很棒的(免费)教程:http://www.raywenderlich.com/51127/nsurlsession-tutorial
答案 2 :(得分:0)
我试过了:
-(void)viewDidAppear:(BOOL)animated
{
dispatch_async(kBgQueue, ^{
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://www.gcap.eu/omosanya/download.php"]];
[self performSelectorOnMainThread:@selector(receivedCall:)withObject:data waitUntilDone:YES];
});
}
- (void) receivedCall:(NSData *)response
{
NSError *error;
NSArray *parsedResponse = [NSJSONSerialization
JSONObjectWithData:response
options:NSJSONReadingMutableContainers
error:&error];
if (error) {
NSLog(@"Error %@", error);
}
NSLog(@"Silly Response %@", parsedResponse);
}
其中:
#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
我收到以下错误:
Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Badly formed array around character 3482608.) UserInfo=0x16512920 {NSDebugDescription=Badly formed array around character 3482608.}
我怀疑问题是JSON格式错误,可以通过调查服务器如何形成JSON来解决问题。
此外,上面的代码可能值得使用 - 它不会阻塞主线程并使用更少的代码实现相同的功能。它也更容易扩展,因为如果您想要并行或顺序进行多个API调用,这可以比您使用的方法更容易实现。