How to use AFNetworking 2.0 synchronously

I looked through a lot of examples and guides for launching AFNetworking 2.0 synchronously and found only solutions for AFNetworking 1.0. What I found: Can AFNetworking return data synchronously (inside a block)?

My example:

- (User *)getUserWithUsername: (NSString *) username andPassword: (NSString *) password {

    NSDictionary *params = @{@"email": username, @"password": password};


    [[DCAPIClient sharedClient] POST:@"login" parameters:params success:^(NSURLSessionDataTask * __unused task, id JSONResult) {
        NSLog(@"JSON %@", JSONResult);
        BOOL errorCode = [JSONResult objectForKey:@"error"];
        if (!errorCode) {
            self.username = [JSONResult objectForKey:@"name"];            
            // Fill the attributes
            // self.email = .. a
         } else {
            // error with login show alert
         }

     } failure:^(NSURLSessionDataTask *__unused task, NSError *error) {
         NSLog(@"error %@", error);
     }];

     // this does not work
     //[[[DCAPIClient sharedClient] operationQueue] waitUntilAllOperationsAreFinished];


     if (self.username == nil) {
         return nil;
     }

     return self;

}

But this does not work, because it if (self.username == nil)is called first.

How can I get AFNetworking 2.0 lib to work synchronously so that I can return a response?

DCAPIClient: AFHTTPSessionManager

+ (instancetype)sharedClient {
    static DCAPIClient *_sharedClient = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedClient = [[DCAPIClient alloc] initWithBaseURL:[NSURL URLWithString:DCAPIBaseURLString]];
        _sharedClient.responseSerializer = [AFJSONResponseSerializer serializer];
    });

    return _sharedClient;
}
+4
source share
3 answers

You should not make a synchronous synchronous synchronous method, but instead make your site host asynchronous.

:

- (void) userWithUsername:(NSString *)username 
                 password:(NSString *)password 
               completion:(completion_handler_t)completion;

completion_handler_t - :

typedef void (^completion_handler_t)(User*, NSError*);

, typedef .

:

[self userWithUsername:username 
              password:password 
            completion:^(User* user, NSError*error){
    // Check error; do something with user
    ...
}];

, :

- (void) userWithUsername:(NSString *)username 
                 password:(NSString *)password 
               completion:(completion_handler_t)completion
{
    NSDictionary *params = @{@"email": username, @"password": password};
    [[DCAPIClient sharedClient] POST:@"login" parameters:params   
        success:^(NSURLSessionDataTask * __unused task, id JSONResult) {
            NSLog(@"JSON %@", JSONResult);
            BOOL errorCode = [JSONResult objectForKey:@"error"];
            if (!errorCode) {
                self.username = [JSONResult objectForKey:@"name"];            
                // Fill the attributes
                // self.email = .. a
                if (completion) {
                    completion(theUser, nil);  // completion(self, nil)?? 
                }
            } else {
                if (completion) {
                    completion(nil, error);
                }
            }

        } failure:^(NSURLSessionDataTask *__unused task, NSError *error) {
             if (completion) {
                 completion(nil, error);
             }
        }];
}
0

, , HTTP- .

AFNetworking-Synchronous. AFHTTPRequestOperationManager , syncGET syncPOST, AFNetworking waitUntilFinished .

+5

I'm not sure why you are doing this, but one solution would be to use callback blocks. Something like that:

- (void)getUserWithUsername: (NSString *) username andPassword: (NSString *) password success:(void (^)(User *user))success failure:(void (^)(NSError *error))failure
{
    NSDictionary *params = @{@"email": username, @"password": password};

    __weak __typeof(self)weakSelf = self;    

    [[DCAPIClient sharedClient] POST:@"login" parameters:params success:^(NSURLSessionDataTask * __unused task, id JSONResult) {

        BOOL errorCode = [JSONResult objectForKey:@"error"];
        if (!errorCode) {
            weakSelf.username = [JSONResult objectForKey:@"name"];

            if (weakSelf.username == nil) {
                failure(nil);
            }else{
                success(weakSelf)
            }
        } else {
            failure(nil);
        }

    } failure:^(NSURLSessionDataTask *__unused task, NSError *error) {
         failure(error);
    }];
}
0
source

Source: https://habr.com/ru/post/1532788/


All Articles