obtenir responseObject sur le bloc d'échec AFNetworking 3.0
Comment puis-je obtenir la chaîne de réponse du bloc d'échec dans AFNetworking 3.x,
Dans le 2.X version la façon de le faire était:
[manager GET:path parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSDictionary *dictionary_FetchResult = responseObject;
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSDictionary *dictionary_FetchResult = operation.responseObject;
}];
Mais dans le 3.X version il n'y a pas d'opération dans le paramètre du bloc de retour comme indiqué ci-dessous:
[manager POST:path parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSDictionary *dictionary_FetchResult = responseObject;
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"Error: %@", error);
}];
J'espérais donc que quelqu'un puisse y parvenir.
23
demandé sur
Moritz
2016-01-29 14:21:36
6 réponses
Faites simplement ceci dans votre bloc d'échec: -
NSString* errResponse = [[NSString alloc] initWithData:(NSData *)error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] encoding:NSUTF8StringEncoding];
NSLog(@"%@",errResponse);
Pour Swift:-
var errResponse: String = String(data: (error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] as! NSData), encoding: NSUTF8StringEncoding)
NSLog("%@", errResponse)
Mise à Jour pour Swift 4.1
var errResponse: String = String(data: (error._userInfo![AFNetworkingOperationFailingURLResponseDataErrorKey] as! Data), encoding: String.Encoding.utf8)!
print(errResponse)
51
répondu
Vizllx
2018-03-03 02:50:15
J'ai trouvé une solution qui fonctionne parfaitement. Dans swift
if let userInfo : NSDictionary = error.userInfo as NSDictionary {
if let innerError : NSError = userInfo.objectForKey("NSUnderlyingError") as? NSError {
if let innerUserInfo : NSDictionary = innerError.userInfo as NSDictionary {
if innerUserInfo.objectForKey(AFNetworkingOperationFailingURLResponseDataErrorKey) != nil {
let StrError = NSString(data: innerUserInfo.objectForKey(AFNetworkingOperationFailingURLResponseDataErrorKey) as! NSData, encoding: NSUTF8StringEncoding)
print(StrError)
}
} else if let errResponse: String = String(data: (error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] as! NSData), encoding: NSUTF8StringEncoding) {
print(errResponse)
}
}
}
Et le code Objective-C est
NSDictionary *userinfo1 = [[NSDictionary alloc] initWithDictionary:error.userInfo];
if(userinfo1) {
NSError *innerError = [userinfo1 valueForKey:@"NSUnderlyingError"];
if(innerError) {
NSDictionary *innerUserInfo = [[NSDictionary alloc] initWithDictionary:innerError.userInfo];
if(innerUserInfo)
{
if([innerUserInfo objectForKey:AFNetworkingOperationFailingURLResponseDataErrorKey])
{
NSString *strError = [[NSString alloc] initWithData:[innerUserInfo objectForKey:AFNetworkingOperationFailingURLResponseDataErrorKey] encoding:NSUTF8StringEncoding];
NSLog(@"Error is : %@",strError);
}
}
} else
{
NSString *errResponse = [[NSString alloc] initWithData:[userinfo1 valueForKey:@"AFNetworkingOperationFailingURLResponseDataErrorKey"] encoding:NSUTF8StringEncoding];
if(errResponse)
{
NSLog(@"%@",errResponse);
}
}
}
5
répondu
Max
2016-06-28 05:51:26
- (void)requestWithURL:(NSString *)url parameterDictionary:(NSMutableDictionary *)data requestType:(NSString *)reqType handler:(NSObject *)handler selector:(SEL)selector
{
// reqType is POST or GET
// handler would be self if you define selector method in same class
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:reqType URLString:[NSString stringWithFormat:@"%@",url] parameters:nil error:nil];
req.timeoutInterval= [[[NSUserDefaults standardUserDefaults] valueForKey:@"timeoutInterval"] longValue];
[req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
if (data != nil) {
NSLog(@"Data is not nil");
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:data options:0 error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
[req setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
}else{
NSLog(@"Data is nil");
}
[[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (!error) {
// NSLog(@"Reply JSON: %@", responseObject);
[handler performSelector:selector withObject:responseObject];
if ([responseObject isKindOfClass:[NSDictionary class]]) {
//blah blah
}
} else {
NSLog(@"Error: %@, %@, %@", error, response, responseObject);
[handler performSelector:selector withObject:responseObject];
}
}] resume];
}
2
répondu
Avinash Jadhav
2016-03-16 08:18:00
J'ai trouvé une solution à GitHub :
@interface ResponseSerializer : AFJSONResponseSerializer
@end
@implementation ResponseSerializer
- (id)responseObjectForResponse:(NSURLResponse *)response
data:(NSData *)data
error:(NSError *__autoreleasing *)errorPointer
{
id responseObject = [super responseObjectForResponse:response data:data error:errorPointer];
if (*errorPointer) {
NSError *error = *errorPointer;
NSMutableDictionary *userInfo = [error.userInfo mutableCopy];
userInfo[@"responseObject"] = responseObject;
*errorPointer = [NSError errorWithDomain:error.domain code:error.code userInfo:[userInfo copy]];
}
return responseObject;
}
@end
Puis attribuez - le à votre gestionnaire:
self.manager.responseSerializer = [ResponseSerializer serializer];
0
répondu
landonandrey
2016-06-15 14:56:05
let responseData:NSData = (error as NSError).userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] as! NSData
let s :String = String(data: responseData as Data, encoding: String.Encoding.utf8)!
Pour Swift 3
0
répondu
user1969245
2016-11-25 12:13:39
Correction du code ici, en manipulant correctement les options. Swift 3(.1)...
let nserror = error as NSError
if let errordata = nserror.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] as? Data {
if let errorResponse = String(data: errordata, encoding: String.Encoding.utf8) {
print("errorResponse: \(errorResponse)")
}
}
0
répondu
Jonny
2017-11-13 01:51:40