尝试使用API类从URL获取数据,然后将该数据返回到ViewController内的方法。我有ViewController调用API方法。
已经在SO上尝试了几个地方,并提出了以下内容,但是它没有用,而且作为一个Objective-C noobie尝试过阅读文档,但仍然没有理解可能出现的问题。
我有一个viewcontroller在类'api'中调用方法'fetch'
我在api类中有连接委托,它工作正常(正确的数据打印在connectionDidFinishLoading
方法内)
我需要一个委托将数据返回到viewcontroller类中的方法。
到目前为止我已经
了ViewController.h
#import "Api.h"
@interface ViewController : UIViewController <apiDelegate>{
}
- (void)apiSucceeded:(NSString *)jsonString;
- (void)apiFailed:(NSString *)failedMessage;
@end
ViewController.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'的问题。这一点运行良好,它将数据BACK传递给导致问题的ViewController。
有人能看到我做错了吗?
答案 0 :(得分:2)
我似乎忘了设置
myapi.delegate = self;
后
Api* myapi = [[Api alloc]init];