2016-08-19 61 views
1

您好我正在做一個單身爲JSON和XML響應不能讓單身的JSON和AFNetworking 3

我ApiClient.h

+ (ApiClient *)sharedInstance; 

-(instancetype)initWithBaseURL:(NSURL *)url sessionConfiguration:(NSURLSessionConfiguration *)configuration; 

我ApiClient.m

聯網
+ (ApiClient *)sharedInstance { 
    static ApiClient *sharedInstance = nil; 

    static dispatch_once_t oncePredicate; 
    dispatch_once(&oncePredicate, ^{ 
     NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration]; 
     sharedInstance = [[self alloc] initWithBaseURL:[NSURL URLWithString:SINGPOST_BASE_URL] sessionConfiguration:sessionConfiguration]; 

     [sharedInstance setDataTaskWillCacheResponseBlock:^NSCachedURLResponse *(NSURLSession *session, NSURLSessionDataTask *dataTask, NSCachedURLResponse *proposedResponse) 
     { 
      NSHTTPURLResponse *resp = (NSHTTPURLResponse*)proposedResponse.response; 
      NSMutableDictionary *newHeaders = [[resp allHeaderFields] mutableCopy]; 
      if (newHeaders[@"Cache-Control"] == nil) { 
       newHeaders[@"Cache-Control"] = @"max-age=120, public"; 
      } 
      NSURLResponse *response2 = [[NSHTTPURLResponse alloc] initWithURL:resp.URL statusCode:resp.statusCode HTTPVersion:nil headerFields:newHeaders]; 
      NSCachedURLResponse *cachedResponse2 = [[NSCachedURLResponse alloc] initWithResponse:response2 
                          data:[proposedResponse data] 
                         userInfo:[proposedResponse userInfo] 
                        storagePolicy:NSURLCacheStorageAllowed]; 
      return cachedResponse2; 
     }]; 
    }); 
    return sharedInstance; 
} 
-(instancetype)initWithBaseURL:(NSURL *)url sessionConfiguration:(NSURLSessionConfiguration *)configuration { 
    self = [super initWithBaseURL:url sessionConfiguration:configuration]; 
     if (self) { 
     } 
    return self; 
} 

問題是單例無法處理XML和JSON響應。它可以成功解析JSON和XML一次。但是,當再次調用再次解析)(後成功地解析XML)的結果將不被正確地解析(給出十六進制字符串響應)

我的JSON塊請求

- (void)sendJSONRequest:(NSMutableURLRequest *)request 
       success:(void (^)(NSURLResponse *response, id responseObject))success 
       failure:(void (^)(NSError *error))failure { 

    self.responseSerializer.acceptableContentTypes = [AFHTTPResponseSerializer serializer].acceptableContentTypes; 

    NSURLSessionDataTask *dataTask = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { 
     if (error) { 
      NSLog(@"Error URL: %@",request.URL.absoluteString); 
      NSLog(@"Error: %@", error); 
      failure(error); 
     } else { 
      NSDictionary *jsonDict = (NSDictionary *) responseObject; 
      success(response,jsonDict); 
      NSLog(@"Success URL: %@",request.URL.absoluteString); 
      NSLog(@"Success %@",jsonDict); 
     } 
    }]; 
    [dataTask resume]; 

} 

我的XML塊請求

- (void)sendXMLRequest:(NSMutableURLRequest *)request 
       success:(void (^)(NSURLResponse *response, RXMLElement *responseObject))success 
       failure:(void (^)(NSError *error))failure { 

    self.requestSerializer = [AFHTTPRequestSerializer serializer]; 
    self.responseSerializer = [AFHTTPResponseSerializer serializer]; 
    [self.responseSerializer.acceptableContentTypes setByAddingObject:@"application/xml"]; 
    NSURLSessionDataTask *dataTask = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { 
     if (error) { 
      NSLog(@"Error URL: %@",request.URL.absoluteString); 
      NSLog(@"Error: %@", error); 
      failure(error); 
     } else { 
      RXMLElement *rootXml = [RXMLElement elementFromXMLData:responseObject]; 
      success(response, rootXml); 
      NSLog(@"Success URL: %@",request.URL.absoluteString); 
      NSLog(@"Success %@",rootXml); 

     } 
    }]; 
    [dataTask resume]; 
} 

我的十六進制字符串失敗反應: enter image description here

反正讓單身正常工作或我需要2單對於j SON和XML響應?任何幫助非常感謝。謝謝!

+0

只顯示我們的十六進制字符串失敗是不夠的,因爲這只是向我們展示了響應的JSON正文。你也應該分享錯誤信息。 – Rob

回答

1

您的錯誤很可能會告訴您,它期望Content-Typeapplication/xml,並且您可能有application/json。很難說,因爲你沒有分享完整的錯誤,但可能是這樣的。

有兩種邏輯方法。可以是:

  1. 有單個AFHTTPSessionManager接受XML和JSON。因此,的AFHTTPResponseSerializeracceptableContentTypesapplication/xmlapplication/json(或任何具體的Content-Type您的兩個Web服務都會返回),然後當您收到NSData響應對象時,或者根據需要解析XML或JSON。

  2. 具有單獨AFHTTPSessionManager對象,一個XML(具有AFXMLResponseSerializerresponseSerializer),一個用於JSON(具有AFJSONResponseSerializerresponseSerializer)。請注意,如果您這樣做,則根本不需要調整acceptableContentTypes

+0

非常感謝您的幫助。我設法使用1個單例AFHTTPSessionManager。訣竅是我們需要設置正確的XML或JSON請求和響應序列化程序:self.requestSerializer = [AFJSONRequestSerializer serializer];對於JSON和self.requestSerializer = [AFHTTPRequestSerializer serializer];對於XML。你知道我們可以使用2或3個基本URL嗎? –

+0

不要擔心基本URL。如果會話正在訪問單個服務器,那麼這很有用,否則,請不要使用基本URL並提供請求的完整URL,並且它會將基本URL排除在等式之外。 – Rob

+0

那麼基本URL是做什麼的?我認爲它用於更快地連接或爲相同的連接保存一些信息? –