2012-06-06 42 views
2

我被一些疯狂的东西卡住了。我使用ASIHTTPRequest从Web服务接收我的数据,一切正常。我切换到使用NSURLConnection,我收到相同的数据并以相同的方式解析,但我的代码无法识别NSURLConnection的数据。NSURLConnection和JSON数据

这是我收到(从NSLog

Did receive data: {"d":"[{\"id\":1.0,\"Category\":1,\"hPlan\":0.0,\"Tip\":\"It takes 3500 
calories to gain a pound. If you want to lose a pound per week, reduce your calorie 
intake by 250 calories and incorporate daily physical activity that will burn 250 
calories.\",\"TipDate\":\"2012-05-12T00:00:00\",\"TimeStamp\":\"AAAAAAAAB9I=\"}]"} 


2012-06-06 09:42:11.809 StaticTable[27488:f803] Jsson Array: 0 
2012-06-06 09:42:11.809 StaticTable[27488:f803] Jsson Array: (null) 

代码数据:

#import "UYLFirstViewController.h" 
#import "MBProgressHUD.h" 
#import "JSON.h" 

@interface UYLFirstViewController() 

@end 

@implementation UYLFirstViewController 

#pragma mark - 
#pragma mark === UIViewController === 
#pragma mark - 

@synthesize MessageField; 
@synthesize jsonArray = _jsonArray; 
@synthesize TipLabelField; 


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 
{ 
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; 
if (self) { 
    self.title = NSLocalizedString(@"Tickle!", @"Tickle!"); 
    self.tabBarItem.image = [UIImage imageNamed:@"heart_plus"]; 

    [self GetTipOfDay]; 

} 
return self; 
} 

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation 
{ 
    return YES; 
} 
-(BOOL)GetTipOfDay{ 

NSDate *date = [NSDate date]; 

NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init]; 
[dateFormat setDateFormat:@"EEEE MMMM d, YYYY"]; 
NSString *dateString = [dateFormat stringFromDate:date]; 


NSString *yourOriginalString = @"Tip of the Day for "; 

yourOriginalString = [yourOriginalString stringByAppendingString:dateString]; 
TipLabelField.text = yourOriginalString; 


NSURL *url = [NSURL URLWithString:@"http://www.mysite.com/api/GetHealth.asmx/getTipOfDay"]; 


NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url]; 
[request setHTTPMethod:@"GET"]; 
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"]; 
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 

[NSURLConnection connectionWithRequest:request delegate:self]; 



// Clear text field 
MessageField.text = @""; 

// Start hud 
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES]; 
    hud.labelText = @"Gathering Tip of the Day..."; 

return TRUE; 

} 

- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{ 

[MBProgressHUD hideHUDForView:self.view animated:YES]; 


NSLog(@"Did receive data: %@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]); 


NSDictionary *responseDict = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] JSONValue]; 

NSString *jsonResponse = [responseDict objectForKey:@"d"]; 

self.jsonArray = [jsonResponse JSONValue]; 


NSLog(@"Jsson Array: %d", [jsonArray count]); 
NSLog(@"Jsson Array: %@", jsonArray); 


NSEnumerator *myEnumerator; 
myEnumerator = [jsonArray objectEnumerator]; 
int i; 
i=0; 
id myObject; 

while (myObject = [myEnumerator nextObject]) 
{ 
    NSDictionary *itemAtIndex = (NSDictionary *)[self.jsonArray objectAtIndex:i]; 

    NSLog(@"Checking for games"); 

    NSString *myCheck = [itemAtIndex objectForKey:@"FName"]; 

    if ([myCheck length] != 0) 
    { 
     // NSLog(myCheck); 
     MessageField.text = myCheck; 
    } 
} 

} 



- (void)viewDidUnload { 
[self setMessageField:nil]; 
[self setTipLabelField:nil]; 
[super viewDidUnload]; 
} 
@end 


#import <UIKit/UIKit.h> 

@interface UYLFirstViewController : UIViewController{ 
    NSMutableArray *jsonArray; 
} 
@property (weak, nonatomic) IBOutlet UILabel *MessageField; 
@property (weak, nonatomic) NSMutableArray *jsonArray; 
@property (weak, nonatomic) IBOutlet UILabel *TipLabelField; 

-(BOOL)GetTipOfDay; 


@end 
+0

你可以发布你的文件的完整代码,所以我们可以有更好的看看发生了什么? – ophychius

+0

@Ed F我没有在代码中看到正确实现NSURLConnection所需的任何委托方法:) – self

+0

我已添加完整文件 –

回答

3

-didRecieveData可以被多次作为字节块进来你应该将你的逻辑到-connectionDidFinishLoading。当连接完成并且数据准备好被分析时,这会让你知道。

2

NSURLConnection如果你只是做了一个简单的GET请求(并且你正在开发一个支持块的iOS版本),那么它有点矫枉过正。您可以在dispatch_async块做到这一点:

- (void) getData 
{ 
    dispatch_async(<some_queue>, ^{ 

     NSError * error = nil; 
     NSString * response = [NSString stringWithContentsOfURL: stringWithContentsOfURL: requestUrl error: &error]; 

     // process JSON 

     dispatch_async(dispatch_get_main_queue(), ^{ 

      // Update UI on main thread 

     } 

    }); 
} 

你可以从我的例子代码中看到的,你也可以在后台排队进行您的JSON处理(前提是你要调用的方法是线程安全的)。只需传回主队列即可更新用户界面。

+0

即使当我这样做我的JSON字符串没有被放入数组似乎就像。该数组总是空的。 –

+0

这听起来好像你的JSON字符串无效。尝试粘贴到http://jsonlint.com/来检查它。 –

+0

我去了网站,并输入它,并得到'有效的JSON'的结果。这使我疯狂...... {“d”:“[{\”id \“:1.0,\”Category \“:1,\”hPlan \“:0.0,\”Tip \“:\” 3500卡路里获得一英镑。如果你想每周减掉一磅,减少卡路里摄入量250卡路里,并加入每天可以消耗250卡路里的体力活动。\“,\”TipDate \“:\”2012-05-12T00:00:00 \“ ,\ “时间戳\”:\ “AAAAAAAAB9I = \”}]“} –

3

你只实现NSURLConnectionDelegate方法之一。尝试添加此

- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { 
    //set up *receivedMutableString as instance variable in .h 
    if (!receivedMutableString) { 
     self.receivedMutableString = [[NSMutableString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 
    } else { 
     NSString *dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 
     [receivedMutableString appendString:dataString]; 
    } 
} 


- (void)connectionDidFinishLoading:(NSURLConnection *)connection { 
    //Now receivedMutableString contains all json data 
    ...continue with your code 
} 
0

似乎这个问题与从web服务获取无关。我必须将我的数组定义为__strong。感谢所有的帮助。我对如何做得更好做了一些很好的想法。