我正在尝试使用 API 类从 URL 获取数据,然后将该数据返回到 ViewController 内的方法。我让 ViewController 调用 API 方法。
已经在 SO 上尝试了几个地方并提出了以下建议,但它不起作用,作为一个 Objective-C 菜鸟已经尝试阅读文档等,但仍然不明白可能出了什么问题。
我有一个视图控制器在类“api”中调用方法“fetch”。
我在 api 类中有连接委托,它工作正常(在connectionDidFinishLoading
方法中打印了正确的数据)。
我需要一个委托将数据返回给 viewcontroller 类中的方法。
到目前为止我有
视图控制器.h
#import "Api.h"
@interface ViewController : UIViewController <apiDelegate>{
}
- (void)apiSucceeded:(NSString *)jsonString;
- (void)apiFailed:(NSString *)failedMessage;
@end
视图控制器.m
#import "ViewController.h"
#import "Api.h"
- (void)apiSucceeded:(NSString *)jsonString {
NSLog(@"WORKED");
}
- (void)apiFailed:(NSString *)failedMessage {
NSLog(@"FAILED");
}
- (void)viewDidLoad {
[super viewDidLoad];
Api* myapi = [[Api alloc]init];
[myapi fetch];
}
@end
api.h
@protocol apiDelegate
@required
- (void)apiSucceeded:(NSString *)jsonString;
- (void)apiFailed:(NSString *)failedMessage;
@end
@interface Api : NSObject {
id _delegate;
}
@property (nonatomic, assign) id _delegate;
-(void)fetch;
@end
api.m
#import "Api.h"
#import "ViewController.h"
@synthesize _delegate;
- (void)fetch{
//connection setup....
[NSURLConnection connectionWithRequest:[request autorelease] delegate:self];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[self.receivedData setLength: 0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// NSLog(@"append data");
[self.receivedData appendData:data];
// NSLog(@"Bytes: %d", [receivedData length]);
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
//TODO error handling for connection
if ([_delegate respondsToSelector:@selector(apiFailed:)]) {
[_delegate apiFailed:[error localizedDescription]];
}
NSLog(@"Cannot Connect");
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"DONE. Received Bytes: %d", [self.receivedData length]);
NSString *jsonString = [[NSString alloc] initWithBytes: [receivedData mutableBytes] length:[receivedData length] encoding:NSUTF8StringEncoding];
if ([_delegate respondsToSelector:@selector(apiSucceeded:)]) {
[_delegate apiSucceeded:jsonString];
}
}
@end
没有错误,但它只是不运行 'apiSucceeded' 方法。
请不要将此误解为有关“connectionDidFinishLoading”的问题。那一点效果很好,它将数据返回给导致问题的 ViewController。
任何人都可以看到我做错了什么吗?