gpt4 book ai didi

ios - 不调用 NSURLSessionDataTask 委托(delegate)方法

转载 作者:行者123 更新时间:2023-11-28 18:55:11 25 4
gpt4 key购买 nike

我正在尝试从 API 下载一些 JSON。现在什么都没有打印出来。

我确信路径和 API Key/Value 有效,因为我是通过带有完成处理程序的 NSURLSessionDataTask 完成的,但我想了解如何使用委托(delegate)方法执行相同的操作。

但我似乎无法弄清楚为什么我的委托(delegate)方法没有被调用。

@interface MetaData () <NSURLSessionDelegate, NSURLSessionDataDelegate>

@end

@implementation MetaData
-(void)downloadData
{
NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];

[sessionConfig setHTTPAdditionalHeaders:@{ header : key}];
NSURLSession *defaultSesh = [NSURLSession sessionWithConfiguration:sessionConfig];
NSURLSessionDataTask *dataTask = [defaultSesh dataTaskWithURL:[NSURL URLWithString:path]];
defaultSesh = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil];
[dataTask resume];


}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler
{
NSLog(@"here 2");
}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
NSLog(@"here");
_weaponDictionary = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:nil];
NSLog(@"dictionary: %@", _weaponDictionary);
}

感谢您的帮助。

编辑

defaultSesh = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil];

通过添加该行,我将委托(delegate)设置为自己。所以现在我打印“here 2”但仍然不打印字典...

最佳答案

使用方法

+ (NSURLSession *)sessionWithConfiguration:(NSURLSessionConfiguration *)configuration
delegate:(id<NSURLSessionDelegate>)delegate
delegateQueue:(NSOperationQueue *)queue

正确设置委托(delegate)。

更新:

而且你必须调用didReceiveResponse的完成处理程序

completionHandler

A completion handler that your code calls to continue the transfer, passing a constant to indicate whether the transfer should continue as a data task or should become a download task.
• If you pass NSURLSessionResponseAllow, the task continues normally.
• If you pass NSURLSessionResponseCancel, the task is canceled.
• If you pass NSURLSessionResponseBecomeDownload as the disposition, your delegate’s URLSession:dataTask:didBecomeDownloadTask: method is called to provide you with the new download task that supersedes the current task.

例如

- (void) URLSession:(NSURLSession *)session 
dataTask:(NSURLSessionDataTask *)dataTask
didReceiveResponse:(NSURLResponse *)response
completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
completionHandler(NSURLSessionResponseAllow);
}

关于ios - 不调用 NSURLSessionDataTask 委托(delegate)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34698102/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com