gpt4 book ai didi

ios:带有返回值的 NSURLRequest 的方法

转载 作者:行者123 更新时间:2023-11-28 22:00:29 27 4
gpt4 key购买 nike

我有一个向 api 发出特定请求的方法,我想从中返回结果。这是我的方法:

-(NSDictionary *) getProfileDataForUser:(NSString *)user_id {
NSURL *getProfileDataRequestURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@users/profile.php?user_id=%@", _apiRootUrl, user_id]];
NSMutableURLRequest *getProfileDataRequest = [NSMutableURLRequest requestWithURL:getProfileDataRequestURL cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:10.0f];
[getProfileDataRequest setHTTPMethod:@"GET"];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:getProfileDataRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
error = nil;
id jsonData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
if (jsonData != nil && error == nil) {
NSDictionary *responseDict = jsonData;
if ([responseDict objectForKey:@"user"]) {
// this is a dictionary
return [responseDict objectForKey:@"user"];
} else {
return responseDict;
}
}
else {
return @{};
}
}];

问题是我遇到了多个语义问题:

sendAsynchronousRequest 方法出错:

Incompatible block pointer types sending 'id (^)(NSURLResponse *__strong, NSData *__strong, NSError *__strong)' to parameter of type 'void (^)(NSURLResponse *__strong, NSData *__strong, NSError *__strong)'

返回错误:

Return type 'NSDictionary *' must match previous return type 'id' when block literal has unspecified explicit return type

我已经尝试将我的方法的返回类型更改为 id,并且只返回 jsonData 但我仍然遇到第一个语义问题。我怎样才能使它工作?

最佳答案

url 请求是异步的,因此该方法需要使用 block /回调来返回结果:

- (void) getProfileDataForUser:(NSString *)user_id withCallback:(void (^)(NSDictionary *jsonData))callback {
NSURL *getProfileDataRequestURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@users/profile.php?user_id=%@", _apiRootUrl, user_id]];
NSMutableURLRequest *getProfileDataRequest = [NSMutableURLRequest requestWithURL:getProfileDataRequestURL cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:10.0f];
[getProfileDataRequest setHTTPMethod:@"GET"];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:getProfileDataRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
error = nil;
id jsonData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
callback(jsonData);
}];
}

关于ios:带有返回值的 NSURLRequest 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25267918/

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