0

Hi I'm about to upgrade old project that use AFNetworking 1.2.1 and AFRaptureXMLOperation to AFNetworking 3.1 to meet to ipv6 requirement from Apple. But because AFRaptureXMLOperation is not support for AFNetworking 3.1 Is there anyway to convert and parse JSON, XML? Any help is much appreciate. Thanks!

this my 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

Top line of My 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"];
    }
}

And Some of my ApiClient.m that Parse Json and 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];
}

for 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];
}
Lê Khánh Vinh
  • 2,591
  • 5
  • 31
  • 77
  • We've outlined some of the issues in http://stackoverflow.com/a/38574520/1271826. I think you need to take a stab at this yourself. We're happy to help you if you encounter problems, we really are, but we're not here to write your code for you. So, take it a step at a time, figure out how to do a request in AFNetworking 3.x. Then figure out how to use `NSXMLParser`. Etc. But this question is too broad as it now stands. – Rob Jul 26 '16 at 04:08
  • Thanks for your help. I'm still trying but in the template of AFNetworking 3.x. The class use is AFURLSessionManager instead of AFHTTPSesssionManager. When to use each. I have start a question regarding this http://stackoverflow.com/questions/38602385/afnetworking-3-x-what-is-the-different-between-afhttpsessionmanager-and-afurlses – Lê Khánh Vinh Jul 27 '16 at 01:53

1 Answers1

1

i would suggest to use TABXML for XML Parsing since its the faster one . this is the api github link TBXML Parser

this is a function that i used to get xml data with TBXML Parser it may help you to understand more . u need just to import

#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 {
            myitem.img=@"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];
    });
}

And for Json parsing using AFnetworking 3.x this function can help you :

   -(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);
    }];
MedAmine.Rihane
  • 1,193
  • 10
  • 17
  • Thanks for your info. I'' try yours. Do you know how to send xml request and receive XML response using AFNetworking 3.x as in this question http://stackoverflow.com/questions/38596162/send-post-request-with-xml-body-and-recieve-xml-response-with-afnetworking-3-x – Lê Khánh Vinh Jul 27 '16 at 01:55