这就是我的结局!应该对以后路过这里的人有用。
#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
他们
#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;
}
优视.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:https ://github.com/erica/iOS-5-Cookbook
BSD 许可证。