首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从NSURLSessionDataTask返回数据

如何从NSURLSessionDataTask返回数据
EN

Stack Overflow用户
提问于 2014-01-01 17:57:02
回答 4查看 14.6K关注 0票数 8

我有一个注册视图控制器,它处理所有用户输入,并调用传递给它的另一个类(wsClass)中的函数,该数据作为一个NSDictionary。

调用wsClass中的函数,建立连接,并从服务器返回数据,并且在会话中可用。

我的问题是如何将数据返回到函数最初调用的注册视图控制器,它始终是空的。

下面是registrationViewController中的调用:

代码语言:javascript
复制
        wsClass *ws = [[wsClass alloc] init];
    NSDictionary *testDict = [[NSDictionary alloc] initWithObjectsAndKeys:username.text,@"username",email.text,@"email",password.text,@"password", nil];
    NSDictionary *respDict = [ws sendData:testDict];

下面是wsClass.m中调用的函数:

代码语言:javascript
复制
- (NSDictionary *)sendData:(NSDictionary *)sendDict {
NSMutableString *sendStr = [[NSMutableString alloc] init];

[sendDict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
    [sendStr appendFormat:@"&%@=%@", key, obj];
}];

NSLog(@"sendStr is: %@",sendStr);
NSString *noteDataString = [NSString stringWithFormat:@"%@%@",REQUIRED,sendStr];

NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlTest]];
request.HTTPBody = [noteDataString dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPMethod = @"POST";

NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request
                                                completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                    // The server answers with an error because it doesn't receive the params
                                                    // handle response
                                                    if(error == nil)
                                                    {
                                                        [getReqAlert dismissWithClickedButtonIndex:0 animated:YES];

                                                        NSError *e = nil;
                                                        jsonArray = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableLeaves error: &e];

                                                        if (!jsonArray) {
                                                            NSLog(@"Error parsing JSON: %@", e);
                                                        } else {

                                                            NSLog(@"resp: %@ = %@",[jsonArray objectForKey:@"status"],[jsonArray objectForKey:@"msg"]);
                                                            NSLog(@"Dictionary count: %lu", jsonArray.count);
                                                        }
                                                    }
                                                }];

 [postDataTask resume];

return jsonArray;

}

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2014-01-01 18:10:35

post异步完成,所以您的wsClass需要在post完成后告诉调用者完成。这样做的一个好方法是使用调用方提供的代码块来增强sendData方法,这些代码应该在完成后运行:

sendData:改为如下所示:

代码语言:javascript
复制
// it doesn't return anything, because all it does is launch the post
// but when the post is done, it invokes completion

- (void)sendData:(NSDictionary *)sendDict completion:(void (^)(NSDictionary *))completion {

    // the stuff you're already doing

        NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request
            completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            // the stuff you're already doing
            // now tell the caller that you're done
            completion(jsonArray);
        }];
    }

呼叫者现在看起来如下:

代码语言:javascript
复制
// change the UI to say "I'm busy doing the post"
[ws sendData:testDict completion:^(NSDictionary *responseDict) {
    NSLog(@"this runs later, after the post completes %@", responseDict);
    // change the UI to say "The post is done"
}];

关于这一点,只需注意几个问题:(1)我没有在块中添加错误param,您可能应该这样做。检查它,并使用零和错误调用块,或者用json输出和error=nil调用块。(2)您的代码假定json结果解析为字典。在代码中假设之前,请确保这始终是正确的。(3)类名通常以大写开头。

票数 16
EN

Stack Overflow用户

发布于 2016-09-21 13:21:48

您可以使用信号量直到块完成执行,然后从函数返回值。

代码语言:javascript
复制
- (NSDictionary *)sendData:(NSDictionary *)sendDict {
NSMutableString *sendStr = [[NSMutableString alloc] init];

[sendDict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
[sendStr appendFormat:@"&%@=%@", key, obj];
}];

NSLog(@"sendStr is: %@",sendStr);
NSString *noteDataString = [NSString stringWithFormat:@"%@%@",REQUIRED,sendStr];

NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlTest]];
request.HTTPBody = [noteDataString dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPMethod = @"POST";


 let semaphore = dispatch_semaphore_create(0)

NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
// The server answers with an error because it doesn't receive the params
// handle response
if(error == nil)
{
[getReqAlert dismissWithClickedButtonIndex:0 animated:YES];

NSError *e = nil;
jsonArray = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableLeaves error: &e];

if (!jsonArray) {
NSLog(@"Error parsing JSON: %@", e);
} else {

NSLog(@"resp: %@ = %@",[jsonArray objectForKey:@"status"],[jsonArray objectForKey:@"msg"]);
NSLog(@"Dictionary count: %lu", jsonArray.count);

     dispatch_semaphore_signal(semaphore)
}
}
}];

[postDataTask resume];
 dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
return jsonArray;

}

票数 1
EN

Stack Overflow用户

发布于 2014-09-27 19:45:50

这也许能行。

  1. 添加一个接口变量nsDictVariable,用于NSDict或类中检索的任何内容
  2. 在SendData中赋值: self.nsDictVariable =.
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20871506

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档