我是相對較新的Objective-C但掙扎與NSURLConnection委託。下面我有一個執行文件api.m當NSURLConnection委託自己如何返回didReceiveData和didReceiveResponse我的方法
在我的viewcontrollers的其他地方,我用方法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