简体   繁体   中英

NSURLConnection and JSON Data

I am stuck with something crazy. I used ASIHTTPRequest to receive my data from a web service and everything worked fine. I switched to using a NSURLConnection and I am receiving the same data and parsing it the same way but my code won't recognize the data with the NSURLConnection .

Here is the data I am receiving (from 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)

Code:

#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

-didRecieveData can be called multiple times as the bytes and chunks come in. You should move your logic to -connectionDidFinishLoading . This will let you know when the connection is completely done and the data is ready to be parsed.

You're only implementing one of the NSURLConnectionDelegate methods. Try adding this

- (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 
}

NSURLConnection is a bit of overkill if you're just doing a simple GET request (and you're developing for an iOS version that supports blocks). You can do this in a dispatch_async block:

- (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

        }

    });
}

As you can see from my example code, you can also perform your JSON processing on the background queue (provided the method you're calling is thread safe). Just pass back to the main queue to update the UI.

Seems like the issue had nothing to do with fetching from the webservice. I had to define my array as __strong. Thanks for all the help. I did get some good ideas on how to do things better.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM