我对objective-c 相对较新,但在涉及NSURLConnection 时与代表苦苦挣扎。下面我有一个实现文件 api.m
在我的视图控制器的其他地方,我使用 getGroups 方法调用这个 api 对象,这里的目的是返回在发出 API 请求时找到的组数。我可以在 didReceiveData 中看到数据,但我怎样才能将这些数据返回到我的 getGroups 中,以便我可以在我的 viewController 中访问它?
在我的视图控制器中,我有类似的东西:
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