首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从异步NSURLConnection/类返回NSDictionary

从异步NSURLConnection/类返回NSDictionary
EN

Stack Overflow用户
提问于 2012-06-16 09:59:21
回答 2查看 565关注 0票数 0

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

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

代码语言:javascript
复制
- (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?

EN

回答 2

Stack Overflow用户

发布于 2012-06-16 10:09:31

您需要的是在异步API (具体地说,是[NSURLConnection start])之上的同步操作。如果没有一些繁重的线程杂耍,你就不能做到这一点,而且无论如何这都不是一个好主意--异步确实是个不错的选择。不要丢弃异步性。

执行一次性异步检索方法的最好方法是建立一个方法,该方法以URL、NSObject和选择器为参数,一旦请求完成,就在所述对象上调用所述选择器,并提供NSDictionary作为参数。这是Objective C进行回调的方式。

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

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

票数 0
EN

Stack Overflow用户

发布于 2012-06-16 14:14:12

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

代码语言:javascript
复制
 #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

The .m

代码语言:javascript
复制
#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

使用-在您的View.h中

代码语言:javascript
复制
#import "LoadURLJson.h"

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

youView.m

通过以下方式进行呼叫:

代码语言:javascript
复制
loadJson = [LoadURLJson download:@"url" withDelegate:self];

然后实现

代码语言:javascript
复制
-(void)downloadFinished
{
    NSData *data = [[NSData alloc] initWithData:loadJson.receivedData];

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

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

基于这里的DownloadHelper:https://github.com/erica/iOS-5-Cookbook

BSD牌照。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11060187

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档