我正在尝试在某些网址上发送 post 请求,并且正文中仅包含 json 数据(尝试注册新用户发送 json
{
"username": "test",
"password": "test",
"email": "email@gmail.com"
}
我有类似的功能
-(NSString*) sendPostOnUrl:(NSString*) url
withParameters:(NSDictionary*)params{
__block NSString* response = nil;
NSError *error;
NSURL *u = [NSURL URLWithString:url];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL: u];
[httpClient postPath:REGISTER
parameters:params
success:^(AFHTTPRequestOperation *operation, id responseObject) {
response = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(@"Request Successful, response '%@'", response);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"[HTTPClient Error]: %@", error.localizedDescription);
}];
return response;
}
其中 params 是 NSDictionary,其中包含用户名、密码和电子邮件键以及这些键的值。 问题是,当我发送时,我总是返回 null 响应(最新行),但在 NSLog 中我得到 json 响应。我对 ios 很陌生,在我看来,我需要以某种方式与 return 同步从功能,但不知道如何,有人可以告诉我我做错了什么吗? (当我尝试调试时,params 包含所有这些键,url 没问题,REGISTER 是 NSString 常量)
最佳答案
block 是异步的 - 这里的问题是“response = [[NSString alloc] initWithData...”位于退出该方法后执行的 block 内。更好的方法是不要在方法中执行此操作,而是将此代码放在调用 sendPostOnUrl:withParameters: 的位置,并在 success block 中执行您需要执行的任何操作。所以不是:
self.something = [self sendPostOnUrl:url withParameters:@{"username":"test" etc}];
你这样做:
NSError *error;
NSURL *u = [NSURL URLWithString:url];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL: u];
__weak YourClassName *me = self;
[httpClient postPath:REGISTER
parameters:params
success:^(AFHTTPRequestOperation *operation, id responseObject) {
me.something = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(@"Request Successful, response '%@'", response);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"[HTTPClient Error]: %@", error.localizedDescription);
}];
另外,请注意“__weak YourClassName *me = self”,您不能在 block 中引用 self,因为这会导致保留周期。
关于ios - AFHttpclient 在 block 中获取 json 正文,但外部函数返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14864963/