2

我被一些疯狂的事情困住了。我曾经ASIHTTPRequest从网络服务接收我的数据,一切正常。我切换到使用 aNSURLConnection并且我收到相同的数据并以相同的方式解析它,但我的代码无法识别带有NSURLConnection.

这是我收到的数据(来自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
4

4 回答 4

3

-didRecieveData可以在字节和块进入时多次调用。您应该将逻辑移动到-connectionDidFinishLoading. 这将让您知道连接何时完全完成并且数据已准备好进行解析。

于 2012-06-06T14:35:12.367 回答
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 
}
于 2012-06-06T14:41:23.323 回答
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 处理(前提是您调用的方法是线程安全的)。只需传回主队列即可更新 UI。

于 2012-06-06T14:40:24.237 回答
0

似乎这个问题与从网络服务中获取无关。我必须将我的数组定义为 __strong。感谢所有的帮助。我确实得到了一些关于如何做得更好的好主意。

于 2012-06-07T13:21:47.313 回答