これが私が最終的に得たものです!将来ここを通過する人に役立つはずです。
#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;
}
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 に基づく: https://github.com/erica/iOS-5-Cookbook
BSD ライセンス。