我發現了類似上面的文章,但對於iOS Developer Library(不是MAX OSX之一),它們都非常相似(或者可能具有相同的內容)。 https://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html#//apple_ref/doc/uid/20001836-BAJEAIEE這就是我在最後做的,而不是實現NSURLConnectionDelegate。
結合本教程中的JSONKit:http://www.techtraits.com/jsonkit/爲我完成這項工作。
謹慎的一句話:我必須關閉ARC,因爲JSONKit目前不支持它。
例子:
- (IBAction)callRest:(id)sender {
NSURL *url = [NSURL URLWithString:@"http://www.example.com/Person/123"];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
if(connection) {
responseData = [[NSMutableData alloc] init];
} else {
NSLog(@"connection failed");
}
}
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[responseData appendData:data];
JSONDecoder *decoder = [[JSONDecoder alloc] initWithParseOptions:JKParseOptionNone];
NSDictionary* json = [decoder objectWithData:responseData];
if(json != nil)
{
NSLog(@"First Name %@", [json objectForKey:@"FirstName"]);
NSLog(@"Last Name %@", [json objectForKey:@"LastName"]);
}
}
- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[connection release];
[responseData release];
NSLog(@"connection error");
}
- (void) connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"connection success");
}
我也有申報responseData像.h文件中
@property (retain, nonatomic) NSMutableData *responseData;
而且在.m文件如下:
@synthesize responseData;
只是一個附加的註釋,但iOS版5也會引發本機JSON解析,這真的很有幫助。 – Joshua 2012-03-06 03:45:14