質問

How to reuse AFNetworking object to return result in ios?

I use AFNetworking to connect server to get my data.

But I have to get data on many time in different view controller.

So I think I had to reuse AFNetworking object.

But I don't know how to write when AFNetworking get data , the object can return result to me(Because the result always not get result immediately, it had some get data and connect time).

Is it have to use [NSNotificationCenter defaultCenter] to implement return result?

or have anyone have some nice method? thank you very much.

my object is here:

@implementation CallServerObj
-(void) loadWebserverData:(NSString*)bodyContent andURLPath:(NSString*) urlPath
{
    AFHTTPRequestOperationManager *manager =
    [AFHTTPRequestOperationManager manager];

    manager.responseSerializer.acceptableContentTypes =
    [NSSet setWithObject:@"text/html"];

    //id result ;

    [manager POST:urlPath
       parameters:bodyContent
          success:^(AFHTTPRequestOperation *operation, id responseObject)
          {

              NSLog(@"result:%@", [responseObject objectForKey:@"result"]);
              //result =  [responseObject objectForKey:@"result"];

          }
          failure:^(AFHTTPRequestOperation *operation,NSError *error)
          {
              NSLog(@"error %@,", error);


          }];

}
@end
役に立ちましたか?

解決

Just like you are sending a success and failure block to AFNetworking, you can send block parameters to the loadWebserverData function. So you can change you function like this

-(void) loadWebserverData:(NSString*)bodyContent andURLPath:(NSString*) urlPath withSuccessBlock:(void(^)(id))success andFailureBlock:(void(^)(NSError *))failure
{
    AFHTTPRequestOperationManager *manager =
    [AFHTTPRequestOperationManager manager];

    manager.responseSerializer.acceptableContentTypes =
    [NSSet setWithObject:@"text/html"];

    //id result ;

    [manager POST:urlPath
       parameters:bodyContent
          success:^(AFHTTPRequestOperation *operation, id responseObject)
          {

              NSLog(@"result:%@", [responseObject objectForKey:@"result"]);
              //result =  [responseObject objectForKey:@"result"];
              success(responseObject)

          }
          failure:^(AFHTTPRequestOperation *operation,NSError *error)
          {
              NSLog(@"error %@,", error);

              failure(error);
          }];

}
@end

and call it like this (assuming that myCallServerObj does not get released after making the call)

[myCallServerObj loadWebserverData:yourContent andURLPath:yourPath withSuccessBlock:^(id responseObject){//Your success code here} andFailureBlock:^(NSError * error){//Your failure code here}];

This is just one of the patterns for communication. For an excellent reference see http://www.objc.io/issue-7/communication-patterns.html

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top