gpt4 book ai didi

cocoa - AFNetworking 未在变量中写入响应

转载 作者:行者123 更新时间:2023-12-03 17:54:51 26 4
gpt4 key购买 nike

我在使用 AFNetworking 时遇到问题代码:

#import "SyncProfile.h"
#import "AFNetworking.h"

@implementation SyncProfile: NSObject
@synthesize delegate = _delegate;


- (BOOL)syncProfile {
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSString *token =[userDefaults objectForKey:@"token"];
int user_id = [userDefaults objectForKey:@"user_id"];
if([token length]) {

self.profileData = [[self sendRequest:@"method.get" token:token withUser:user_id andParameters:@"param1,param2"] valueForKeyPath:@"response"];
NSLog(@"%@", self.profileData);

return YES;
} else
return NO;

}

-(id)sendRequest:(NSString *)apiMethod token:(NSString *)token withUser:(int)user_id andParameters:(NSString *)param {

NSMutableString *apiLink = [NSMutableString stringWithFormat:@"https://domain.com/method/%@?uid=%@&fields=%@&access_token=%@", apiMethod, user_id, param, token];
NSURL *url = [[NSURL alloc] initWithString:apiLink];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(@"%@", JSON);
self.req = JSON;
[self myMethod:JSON];

} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(@"Request Failed with Error: %@, %@", error, error.userInfo);
}];
[operation start];
return self.req;
}

- (id)myMethod:(id)data {
NSLog(@"%@",data);
return 0;
}

@end

我需要使用结果 AFNetworking back 方法返回一个变量。但结果给出的时间比方法返回的时间晚得多。当我使用不同的方法来处理结果时,它不会。尝试使用[操作 waitUntilFinished] 但没有任何改变。

Xcode 输出结果:

//Return variable from "sync" method
2013-02-26 23:57:29.793 walkwithme[13815:11303] (null)
//Return from AFN response
2013-02-26 23:57:31.063 walkwithme[13815:11303] {response = ({someJSON})}
//Return from MyMethod
2013-02-26 23:57:31.063 walkwithme[13815:11303] {response = ({someJSON})}

最佳答案

您绝对不想使用任何wait方法。您需要做的是在成功和失败 block 中进行回调。您可以按照我在 this question 中展示的方式执行此操作您还可以做其他事情,例如消息传递。要认识到的关键是您不会使用典型的方法返回模式。原因是使用像这样的异步方法,您不知道它何时完成,这就是它使用 block 回调的原因。就像我说的,您绝对不想等待,因为这可能会完全阻止您的应用程序。

编辑:

我在我的一个项目中使用此代码:

声明方法

- (void)postText:(NSString *)text
forUserName:(NSString *)username
ADNDictionary:(NSDictionary *)dictionary
withBlock:(void(^)(NSDictionary *response, NSError *error))block;

然后在这个方法中我将这些参数传递给网络请求。

返回 block 中的值:

if (block) {
block(responseObject, someError);
}

然后我这样调用它:

[[KSADNAPIClient sharedAPI] postText:postText
forUserName:username
ADNDictionary:parameters
withBlock:^(NSDictionary *response, NSError *error)
{
if (error) {
// Deal with error
} else {
// Probably success!
}
}

这样,被调用的方法就会将其值返回给 block 内的调用者方法。我认为它将阻塞推迟给调用者。

关于cocoa - AFNetworking 未在变量中写入响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15098573/

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