我设置了一个名为 WebCalls 的对象类。在本课程中,我进行了 Web 调用并从 HTTPS 服务器返回了一些 JSON。现在这些方法完美运行,我已经测试过并且数据返回正常。但是我的问题是,我无法访问类外返回的数据。
检索数据的代码如下
界面
@interface WebCall : NSObject{
NSString *phoneNumber;
NSString *jsonData;
}
@property (nonatomic, retain) NSMutableData *responseData;
@property (nonatomic, retain) NSString *jsonData;
-(void) getData: (NSString *) link;
@end
Implementation
@implementation WebCall
@synthesize jsonData;
@synthesize responseData;
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[responseData setLength:0];
}
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
self.responseData = nil;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *s = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
jsonData = s;
}
-(void) getData: (NSString *) link{
jsonData = [[NSString alloc] init];
self.responseData = [NSMutableData data];
NSURL * url = [NSURL URLWithString:link];
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setHTTPMethod:@"GET"];
[[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:YES];
}
@end
在接口类中,我有一个名为 jsonData 的字符串。我使用属性和综合来获取和设置它。所以在我进行网络调用后,我将数据分配给 jsonData,我应该能够导入网络调用类,使用 getInfo 方法,返回 jsonData 然后使用
WebCall *wc = [[WebCall alloc] init];
[wc getData:url];
NSLog(@"%@", [c jsonData]);
然而,这只是打印出空值。然而,如果我在收到数据后在 Webcall 类中打印出字符串,它会打印得很好。谁能告诉我我做错了什么?
提前致谢
编辑:更新了完整的实现
我也无法访问方法之外的字符串。我将代码复制到另一个类,并尝试分配 JSON 字符串,然后在正文中再次调用它,它再次出现 null。看来我只能用那种连接方法打印出来。然后似乎清除了字符串
编辑:我试过的
[wc setWebCallDidFinish:^(NSString * json, NSString *test){
NSLog(@"%@", json);
}];
[wc getData:@"12345"];