2016-07-26 1 views
0

안녕하세요, Apple에서 ipv6 요구 사항을 충족하기 위해 AFNetworking 1.2.1 및 AFRaptureXMLOperation을 AFNetworking 3.1에 사용하는 기존 프로젝트를 업그레이드하려고합니다. 그러나 AFRaptureXMLOperationAFNetworking을 지원하지 않기 때문에 3.1 어쨌든 JSON, XML을 변환하고 구문 분석합니까? 어떤 도움이라도 대단히 감사합니다. 감사!AFNetworking 3.x 마이그레이션 및 XML 파서

이 내 ApiClient.h

#import <AFNetworking.h> 
#import <AFRaptureXMLRequestOperation.h> 
#import <RXMLElement.h> 
#import <Realm/Realm.h> 

@class Stamp; 

@interface ApiClient : AFHTTPClient 

+(BOOL)isScanner; 
+(BOOL)isWithoutFacebook; 

typedef void (^ApiClientSuccess)(id responseObject); 
typedef void (^ApiClientFailure)(NSError *error); 
typedef void (^ApiClientProgressCompletion)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations); 

+ (ApiClient *)sharedInstance; 

- (void)reportAPIIssueURL:(NSString *)url payload:(NSString *)payload message:(NSString *)message; 

//informations 
- (void)getSingpostContentsOnSuccess:(ApiClientSuccess)success onFailure:(ApiClientFailure)failure; 
- (void)getSendReceiveItemsOnSuccess:(ApiClientSuccess)success onFailure:(ApiClientFailure)failure; 
- (void)getPayItemsOnSuccess:(ApiClientSuccess)success onFailure:(ApiClientFailure)failure; 
- (void)getShopItemsOnSuccess:(ApiClientSuccess)success onFailure:(ApiClientFailure)failure; 
- (void)getServicesItemsOnSuccess:(ApiClientSuccess)success onFailure:(ApiClientFailure)failure; 
- (void)getSingPostAppsItemsOnSuccess:(ApiClientSuccess)success onFailure:(ApiClientFailure)failure; 
- (void)getOffersItemsOnSuccess:(ApiClientSuccess)success onFailure:(ApiClientFailure)failure; 
- (void)getSingpostAnnouncementSuccess:(ApiClientSuccess)success failure:(ApiClientFailure)failure; 

//calculate postage 
- (void)calculateSingaporePostageForFromPostalCode:(NSString *)fromPostalCode andToPostalCode:(NSString *)toPostalCode andWeight:(NSString *)weightInGrams onSuccess:(ApiClientSuccess)success onFailure:(ApiClientFailure)failure; 
- (void)calculateOverseasPostageForCountryCode:(NSString *)countryCode andWeight:(NSString *)weightInGrams andItemTypeCode:(NSString *)itemTypeCode andDeliveryCode:(NSString *)deliveryCode onSuccess:(ApiClientSuccess)success onFailure:(ApiClientFailure)failure; 

//postal codes 
- (void)findPostalCodeForBuildingNo:(NSString *)buildingNo andStreetName:(NSString *)streetName onSuccess:(ApiClientSuccess)success onFailure:(ApiClientFailure)failure; 
- (void)findPostalCodeForLandmark:(NSString *)landmark onSuccess:(ApiClientSuccess)success onFailure:(ApiClientFailure)failure; 
- (void)findPostalCodeForWindowsDeliveryNo:(NSString *)windowsDeliveryNo andType:(NSString *)type andPostOffice:(NSString *)postOffice onSuccess:(ApiClientSuccess)success onFailure:(ApiClientFailure)failure; 

//locations 
- (void)getPostOfficeLocationsOnSuccess:(ApiClientSuccess)success onFailure:(ApiClientFailure)failure; 
- (void)getSamLocationsOnSuccess:(ApiClientSuccess)success onFailure:(ApiClientFailure)failure; 
- (void)getPostingBoxLocationsOnSuccess:(ApiClientSuccess)success onFailure:(ApiClientFailure)failure; 
- (void)getPostalAgentLocationsOnSuccess:(ApiClientSuccess)success onFailure:(ApiClientFailure)failure; 
- (void)getSingPostAgentLocationsOnSuccess:(ApiClientSuccess)success onFailure:(ApiClientFailure)failure; 
- (void)getPopStationLocationsOnSuccess:(ApiClientSuccess)success onFailure:(ApiClientFailure)failure; 

- (void)getLocationsUpdatesOnSuccess:(ApiClientSuccess)success onFailure:(ApiClientFailure)failure; 
- (void)getLocationsUpdatesDetails:(NSArray *)array 
          success:(ApiClientSuccess)success 
          failure:(ApiClientFailure)failure; 

//tracking 
- (void)getItemTrackingDetailsForTrackingNumber:(NSString *)trackingNumber onSuccess:(ApiClientSuccess)success onFailure:(ApiClientFailure)failure; 
- (void)batchUpdateTrackedItems:(NSArray *)trackedItems onSuccess:(ApiClientSuccess)success onFailure:(ApiClientFailure)failure withProgressCompletion:(ApiClientProgressCompletion)progressCompletion; 

//notifications 
- (void)registerAPNSToken:(NSString *)apnsToken onSuccess:(ApiClientSuccess)success onFailure:(ApiClientFailure)failure; 
- (void)subscribeNotificationForTrackingNumber:(NSString *)trackingNumber onSuccess:(ApiClientSuccess)success onFailure:(ApiClientFailure)failure; 
- (void)subscribeNotificationForTrackingNumberArray:(NSArray *)trackingNumberArray onSuccess:(ApiClientSuccess)success onFailure:(ApiClientFailure)failure; 
- (void)unsubscribeNotificationForTrackingNumber:(NSString *)trackingNumber onSuccess:(ApiClientSuccess)success onFailure:(ApiClientFailure)failure; 
- (void)unsubscribeNotificationForTrackingNumberArray:(NSArray *)trackingNumberArray onSuccess:(ApiClientSuccess)success onFailure:(ApiClientFailure)failure; 

//philately 
- (void)getStampsOnSuccess:(ApiClientSuccess)success onFailure:(ApiClientFailure)failure; 
- (void)getImagesOfStamp:(Stamp*)stamp onSuccess:(ApiClientSuccess)success onFailure:(ApiClientFailure)failure; 

//misc 
- (void)getMaintananceStatusOnSuccess:(ApiClientSuccess)success onFailure:(ApiClientFailure)failure; 

//feedback 
- (void)postFeedbackMessage:(NSString *)message subject:(NSString *)subject onSuccess:(ApiClientSuccess)success onFailure:(ApiClientFailure)failure; 

//App update checking 
- (void)checkAppUpdateWithAppVer:(NSString *)appVer andOSVer:(NSString *)osVer; 

//Ad Banner 
-(void) getAdvertisementWithId : (NSString *)locationMasterId Count:(NSString *)count onSuccess:(ApiClientSuccess)success onFailure:(ApiClientFailure)failure; 
-(void) incrementClickCountWithId: (NSString *)locationId onSuccess:(ApiClientSuccess)success onFailure:(ApiClientFailure)failure; 

//Tracking Labeling 
- (void) facebookLoginOnSuccess:(ApiClientSuccess)success onFailure:(ApiClientFailure)failure; 
- (void) isFirstTime:(ApiClientSuccess)success onFailure:(ApiClientFailure)failure; 
- (void) registerTrackingNunmbers: (NSArray *)numbers WithLabels : (NSArray *)labels TrackDetails : (NSArray *) details onSuccess:(ApiClientSuccess)success onFailure:(ApiClientFailure)failure; 
- (void) registerTrackingNunmbersNew: (NSArray *)numbers WithLabels : (NSArray *)labels TrackDetails : (RLMResults *) details onSuccess:(ApiClientSuccess)success onFailure:(ApiClientFailure)failure; 
- (void) getAllTrackingNunmbersOnSuccess:(ApiClientSuccess)success onFailure:(ApiClientFailure)failure; 
- (void) deleteAllTrackingNunmbersOnSuccess:(ApiClientSuccess)success onFailure:(ApiClientFailure)failure; 


@property (nonatomic) NSString * serverToken; 
@property (nonatomic,retain) RLMResults * allTrackingItem; 
@property (nonatomic,retain) NSString * fbToken; 
@property (nonatomic,retain) NSString * fbID; 

@property (nonatomic, readonly) BOOL hasRegisteredProfileId; 
@property (nonatomic) NSString *notificationProfileID; 

@end 

최고 내 ApiClient.m

#import "ApiClient.h" 
#import "EntityLocation.h" 
#import "Stamp.h" 
#import <SSKeychain.h> 
#import "UIAlertView+Blocks.h" 
#import "NSDictionary+Additions.h" 
#import <sys/sysctl.h> 
#import "DeliveryStatus.h" 
#import "Parcel.h" 

#import <AFNetworking/AFNetworking.h> 

@implementation ApiClient 
@synthesize serverToken; 
@synthesize fbToken; 
@synthesize allTrackingItem; 
@synthesize fbID; 

@synthesize notificationProfileID = _notificationProfileID; 

static BOOL isProduction = YES; 
static BOOL isScanner = YES; 
static BOOL isWithoutFacebook = NO; 

+(BOOL)isScanner { 
    return isScanner; 
} 

+(BOOL)isWithoutFacebook { 
    return isWithoutFacebook; 
} 

#define SINGPOST_BASE_URL (isProduction ? SINGPOST_PRODUCTION_BASE_URL:SINGPOST_UAT_BASE_URL) 
#define CMS_BASE_URL  (isProduction ? CMS_PRODUCTION_BASE_URL:CMS_UAT_BASE_URL) 
#define CMS_BASE_URL_V4  (isProduction ? CMS_PRODUCTION_BASE_URL_V4:CMS_UAT_BASE_URL_V4) 
#define AD_BASE_URL   (isProduction ? AD_PRODUCTION_BASE_URL : AD_UAT_BASE_URL) 

//Development 
static NSString *const SINGPOST_UAT_BASE_URL = @"https://uatesb1.singpost.com"; 
static NSString *const CMS_UAT_BASE_URL = @"http://27.109.106.170/mobile2/"; 
static NSString *const CMS_UAT_BASE_URL_V4 = @"http://27.109.106.170/mobile2/v5/"; 
static NSString *const AD_UAT_BASE_URL = @"https://uat.mysam.sg/restful-services/advertisementServices/"; 

//Production 
static NSString *const SINGPOST_PRODUCTION_BASE_URL = @"https://prdesb1.singpost.com"; 
static NSString *const CMS_PRODUCTION_BASE_URL = @"http://mobile.singpost.com/mobile2/"; 
static NSString *const CMS_PRODUCTION_BASE_URL_V4 = @"http://mobile.singpost.com/mobile2/v5/"; 
static NSString *const AD_PRODUCTION_BASE_URL = @"https://www.mysam.sg/restful-services/advertisementServices/"; 

static NSString *const APP_ID = @"M00002"; 
static NSString *const OS = @"ios"; 

//Tracking testing URL 
//static NSString * const TRACKING_TEST_URL = @"https://prdesb1.singpost.com/ma/GetItemTrackingDetailsCentralTnT"; 
//static NSString * const TRACKING_TEST_URL = @"https://uatesb1.singpost.com/ma/GetItemTrackingDetailsCentralTnT"; 

#pragma mark - Shared singleton instance 

+ (ApiClient *)sharedInstance { 
    static ApiClient *sharedInstance = nil; 
    static dispatch_once_t oncePredicate; 
    dispatch_once(&oncePredicate, ^{ 
     sharedInstance = [[self alloc] initWithBaseURL:[NSURL URLWithString:SINGPOST_BASE_URL]]; 
    }); 

    return sharedInstance; 
} 

- (id)initWithBaseURL:(NSURL *)url 
{ 
    if ((self = [super initWithBaseURL:url])) { 
     [AFJSONRequestOperation addAcceptableContentTypes:[NSSet setWithObject:@"text/html"]]; 
    } 

    return self; 
} 

#pragma mark - Properties 

- (BOOL)hasRegisteredProfileId 
{ 
    return [[self notificationProfileID] length] > 0; 
} 

- (NSString *)notificationProfileID 
{ 
    if (!_notificationProfileID) { 
     _notificationProfileID = [SSKeychain passwordForService:KEYCHAIN_SERVICENAME account:@"SETTINGS_PROFILEID"]; 
    } 
    return _notificationProfileID; 
} 

- (void)setNotificationProfileID:(NSString *)inNotificationProfileID 
{ 
    if (inNotificationProfileID.length > 0) { 
     _notificationProfileID = inNotificationProfileID; 
     [SSKeychain setPassword:_notificationProfileID forService:KEYCHAIN_SERVICENAME account:@"SETTINGS_PROFILEID"]; 
    } 
} 

라인 그리고 내 ApiClient.m의 일부 구문 분석 JSON 및 XML

#pragma mark - API calls 

#pragma mark - Informations 

- (void)getSingpostContentsOnSuccess:(ApiClientSuccess)success onFailure:(ApiClientFailure)failure { 
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"singpost-contents.php" 
                       relativeToURL:[NSURL URLWithString:CMS_BASE_URL]]]; 
    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) { 
     if (success) 
      success(JSON); 
    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) { 
     if (failure) 
      failure(error); 
     [self reportAPIIssueURL:[request.URL absoluteString] payload:nil message:[error description]]; 
    }]; 
    [self enqueueHTTPRequestOperation:operation]; 
} 

에 대한 xml :

#pragma mark - Calculate Postage 

- (void)calculateSingaporePostageForFromPostalCode:(NSString *)fromPostalCode 
            andToPostalCode:(NSString *)toPostalCode 
             andWeight:(NSString *)weightInGrams 
             onSuccess:(ApiClientSuccess)success 
             onFailure:(ApiClientFailure)failure { 
    NSString *xml = [NSString stringWithFormat:@"<SingaporePostalInfoDetailsRequest xmlns=\"http://singpost.com/paw/ns\">" 
        "<ToPostalCode>%@</ToPostalCode>" 
        "<FromPostalCode>%@</FromPostalCode>" 
        "<Weight>%@</Weight>" 
        "<DeliveryServiceName></DeliveryServiceName>" 
        "</SingaporePostalInfoDetailsRequest>", toPostalCode, fromPostalCode, weightInGrams]; 

    NSMutableURLRequest *request = [self requestWithMethod:@"POST" path:@"ma/FilterSingaporePostalInfo" parameters:nil]; 
    [request addValue:@"application/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"]; 
    [request addValue:[NSString stringWithFormat:@"%ld", [xml length]] forHTTPHeaderField:@"Content-Length"]; 
    [request setHTTPBody:[xml dataUsingEncoding:NSUTF8StringEncoding]]; 

    AFRaptureXMLRequestOperation *operation = [AFRaptureXMLRequestOperation XMLParserRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, RXMLElement *XMLElement) { 
     if (success) 
      success(XMLElement); 
    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, RXMLElement *XMLElement) { 
     if (failure) 
      failure(error); 
     [self reportAPIIssueURL:[request.URL absoluteString] payload:xml message:[error description]]; 
    }]; 

    [self enqueueHTTPRequestOperation:operation]; 
} 
+0

우리는 http://stackoverflow.com/에 몇 가지 문제를 설명했습니다 a/38574520/1271826. 너 혼자서 찔러야 할 것 같아. 문제가 발생하면 기꺼이 도와 드리겠습니다. 실제로 코드를 작성하지는 않습니다. 그러므로 한 번에 한 걸음 내딛고 AFNetworking 3.x에서 요청하는 방법을 알아보십시오. 그런 다음 어떻게'NSXMLParser'를 사용하는지 알아 내십시오. 그러나이 질문은 현재와 마찬가지로 너무 광범위합니다. – Rob

+0

도움 주셔서 감사합니다. AFNetworking 3.x의 템플릿에서 아직 시도하고 있습니다. 클래스 사용은 AFHTTPSesssionManager 대신 AFURLSessionManager입니다. 각각을 사용할시기. 나는 이것에 관한 질문을 시작했다. http://stackoverflow.com/questions/38602385/afnetworking-3-x-what-is-the-different-between-afhttpsessionmanager-and-afurlses –

답변

1

XML 구문 분석에 TABXML을 사용하는 것이 좋습니다. 이것은 api github 링크입니다.

이것은 TBXML Parser로 XML 데이터를 가져 오는 데 사용되는 함수로 더 많은 정보를 얻을 수 있습니다. u는이 기능이 당신을 도울 수 AFnetworking 3.x를을 사용하여

#import "TBXML+HTTP.h" 
#import "TBXML.h" 


-(void)loadnews:(TBXMLElement *)element{ 

    TBXMLElement *item = [TBXML childElementNamed:@"item" parentElement:element]; 

    do { 
     TBXMLElement *titre = [TBXML childElementNamed:@"title" parentElement:item]; 
     TBXMLElement *desc = [TBXML childElementNamed:@"description" parentElement:item]; 





     TBXMLElement *imgitem = [TBXML childElementNamed:@"enclosure" parentElement:item]; 


     News *myitem=[[News alloc] init]; 
     myitem.titre=[TBXML textForElement:titre]; 
     myitem.desc=[TBXML textForElement:desc]; 


     if(imgitem){ 
      myitem.img=[TBXML valueOfAttributeNamed:@"url" forElement:imgitem]; 

     } 
     else { 
      [email protected]"noimg"; 

     } 












     [self.mytabnews addObject:myitem]; 



    } while ((item = item->nextSibling)); 

    //[self.tablenews performSelectorOnMainThread:@selector(reloadData) 
    //  withObject:nil 
    // waitUntilDone:NO];} 

    dispatch_async(dispatch_get_main_queue(), ^{ 
     [self.tablenews reloadData]; 
    }); 
} 

그리고 JSON 구문 분석을 위해를 가져올 단지 필요

-(void) loadevents{ 

     NSString *path = @"yourapilinkhere"; 
     NSString *escapedPath = [path stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]; 

     AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; 



[manager GET:escapedPath parameters:nil progress:nil success:^(NSURLSessionTask *task, id responseObject) { 
      //NSLog(@"JSON: %@", responseObject); 
    }]; 
+0

정보를 제공해 주셔서 감사합니다. 나는 너를 시험해보고있다. XML 요청을 보내고 AFNetworking 3.x를 사용하여 XML 응답을받는 방법을 알고 있습니까? http://stackoverflow.com/questions/38596162/send-post-request-with-xml-body-rec-ve-xml -response-with-afnetworking-3-x –