2012-06-06 41 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。感謝所有的幫助。我對如何做得更好做了一些很好的想法。