我在使用 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 返回方法返回一个变量。但是结果比方法返回要晚得多。当我使用不同的方法来处理结果时,它不会。尝试使用,[operation 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})}