私はobjective-cには比較的慣れていませんが、NSURLConnectionに関してはデリゲートに苦労しています。以下に実装ファイル api.m があります
ビューコントローラーの別の場所で、メソッド getGroups を使用してこの API オブジェクトを呼び出します。ここでの目的は、API 要求が行われたときに見つかったグループの数を返すことです。didReceiveData でデータを確認できますが、このデータを getGroups に戻して、viewController でアクセスできるようにするにはどうすればよいですか?
私のView Controllerには次のようなものがあります:
NSInteger *numGroups = [apiRequest getGroups];
私の api.m 実装ファイルには、次のものがあります。繰り返しますが、すべてが機能します。didReceiveData からデータを返す方法がわからないので、getGroups メソッドでアクセスできます。
#import "API.h"
#import "Constants.h"
#import "JSONParser.h"
@implementation API
@synthesize user, url, receivedData
-(NSInteger)getGroups {
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10];
[request setValue:APIKEY forHTTPHeaderField:@"apikey"];
[request setHTTPMethod:@"GET"];
[request setURL:url];
NSURLConnection *myConnection;
myConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
//How do I access what was append'd in receivedData below
return 2;
}
/* ----------------------------------------------------------------------------------------
NSURLConnection Delegates
------------------------------------------------------------------------------------------- */
// Check the response code that was returned
- (NSInteger)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
return [httpResponse statusCode];
}
// Take a peak at the data returned.
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSLog(@"DATA: %@", [data description]);
//How to get this information back up into the getGroups method
[receivedData appendData: data];
}
// Close the connection
- (void)connectionDidFinishLoading:(NSURLConnection*)connection {
NSLog(@"Connection Closed.");
}
@end