从Async NSURLConnection / Class返回NSDictionary

时间:2012-06-16 01:59:21

标签: json asynchronous nsdictionary

我要做的是创建一个在调用时返回Json Data的NSDictionary的类。我过去用图像做了同样的事情但是我对如何用NSDictionary实现它有点困惑。

我想要做的是加载视图,然后在后台发送请求以获取一些Json数据(异步)并返回包含要使用的数据的字典。我将在很多不同的视图中加载大量的Json数据,因此它应该是一个可重用的类。

- (id)initWithURL:(NSURL *)url
{
    self = [self init];

    if (self)
    {
        receivedData = [[NSMutableData alloc] init];
        [self loadWithURL:url];
    }

    return self;
}

- (void)loadWithURL:(NSURL *)url    
{
    NSURLConnection *connection = [NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:url]delegate:self];
    [connection start];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [receivedData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [receivedData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{

    NSError *error = nil;

    jsonReturn = [NSJSONSerialization JSONObjectWithData:receivedData options:kNilOptions error:&error];

}

我想过将结果添加到视图可以访问的协议中,但是必须有一个更简单/更清晰的方法吗?有没有办法让它像这样返回NSdictionary:

NSDictionary * dictionary = [LoadURLJSon initWithURL:myurl];

它取回了NSDictionary?

2 个答案:

答案 0 :(得分:0)

您想要的是在异步API(特别是[NSURLConnection start])之上的同步操作。如果没有一些繁重的线程杂耍,你就无法做到这一点,无论如何这都是一个坏主意 - 异步真的是要走的路。不要抛弃异步性。

执行一次性异步检索方法的最佳方法是构建一个方法,该方法将URL,NSObject和选择器作为参数,并且一旦请求完成,就调用上述选择器object,提供NSDictionary作为参数。这是做回调的Objective C方式。

该方法将在内部实例化您的类,传递回调信息,并启动请求。请求完成并将JSON解析为NSDictionary后,您可以在回调[performSelector:]上调用NSObject

如果您想要同步操作,请使用[NSURLConnection sendSynchronousRequest]而不是[NSURLConnection start]

答案 1 :(得分:0)

这就是我最终的结果!它应该对将来通过这里的人有用。

 #import <Foundation/Foundation.h>

@protocol LoadJsonDelegate <NSObject, NSURLConnectionDelegate>
@optional
- (void) downloadFinished;
- (void) downloadReceivedData;
- (void) dataDownloadFailed: (NSString *) reason;
@end

@interface LoadURLJson : NSObject
{
    NSMutableData *receivedData;
    int expectedLength;
}

@property (nonatomic, strong) NSMutableData *receivedData;
@property (strong) NSString *urlString;
@property (weak) id <LoadJsonDelegate> delegate;

-(void)start;
-(void)cancel;

+ (id)download:(NSString *)aURLString withDelegate:(id <LoadJsonDelegate>)aDelegate;

@end

.m

#import "LoadURLJson.h"
#define SAFE_PERFORM_WITH_ARG(THE_OBJECT, THE_SELECTOR, THE_ARG) (([THE_OBJECT respondsToSelector:THE_SELECTOR]) ? [THE_OBJECT performSelector:THE_SELECTOR withObject:THE_ARG] : nil)

@implementation LoadURLJson

@synthesize receivedData, delegate, urlString;

+ (id) download:(NSString *)aURLString withDelegate:(id <LoadJsonDelegate>)aDelegate
{
    if (!aURLString)
    {
        NSLog(@"Error. No URL string");
        return nil;
    }

    LoadURLJson *loadJson = [[self alloc] init];
    loadJson.urlString = aURLString;
    loadJson.delegate = aDelegate;
    [loadJson start];

    return loadJson;
}

-(void)start   
{
    receivedData = [NSMutableData data];
    NSURL *url = [NSURL URLWithString:urlString];

    NSURLConnection *connection = [NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:url]delegate:self];
    [connection start];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [receivedData setLength:0];

    // Check for bad connection
    expectedLength = [response expectedContentLength];
    if (expectedLength == NSURLResponseUnknownLength)
    {
        NSString *reason = [NSString stringWithFormat:@"Invalid URL [%@]", urlString];
        SAFE_PERFORM_WITH_ARG(delegate, @selector(dataDownloadFailed:), reason);
        [connection cancel];
        [self cleanup];
        return;
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [receivedData appendData:data];
    SAFE_PERFORM_WITH_ARG(delegate, @selector(downloadReceivedData), nil);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    SAFE_PERFORM_WITH_ARG(delegate, @selector(downloadFinished), nil);
}

-(void)cleanup
{
    self.urlString = nil;
}

-(void)dealloc
{
    [self cleanup];
}

-(void)cancel
{
    [self cleanup];
}

@end

用法 - 在yourView.h中

#import "LoadURLJson.h"

@interface ViewController : UIViewController <LoadJsonDelegate>
{
    LoadURLJson *loadJson;
}

youView.m

致电:

loadJson = [LoadURLJson download:@"url" withDelegate:self];

然后实施

-(void)downloadFinished
{
    NSData *data = [[NSData alloc] initWithData:loadJson.receivedData];

    NSError *error = nil;
    NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error:&error];

    NSLog(@"%@",dictionary);
}

基于DownloadHelper Here:https://github.com/erica/iOS-5-Cookbook

BSD许可证。