I am trying to integrate payu money payment gateway in my app.
Payumoney collect all information and done transaction and return back to my custom defined url webpage.
My problem is how to get the response code after successful transaction from payu money gateway?
int i = arc4random() % 9999999999;
NSString *strHash = [self createSHA512:[NSString stringWithFormat:#"%d%#",i,[NSDate date]]];
NSString *txnid1 = [strHash substringToIndex:20];
NSLog(#"tnx1 id %#",txnid1);
// NSString *key = #"JBZaLc";
// NSString* salt = #"GQs7yium";
NSString *key = #"gtKFFx";
NSString* salt = #"eCwWELxi";
NSString *amount = dataMoney.usrAmount;
NSString *productInfo = #"App Products Info ";
NSString *firstname = dataMoney.usrName;
NSString *email = dataMoney.usrEmail;
NSString *phone = dataMoney.usrMobile;
NSString *surl = #"https://dl.dropboxusercontent.com/s/dtnvwz5p4uymjvg/success.html";
NSString *furl = #"https://dl.dropboxusercontent.com/s/z69y7fupciqzr7x/furlWithParams.html";
NSString *hashValue = [NSString stringWithFormat:#"%#|%#|%#|%#|%#|%#|||||||||||%#",key,txnid1,amount,productInfo,firstname,email,salt];
NSString *hash = [self createSHA512:hashValue];
NSDictionary *parameters = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:txnid1,key,amount,productInfo,firstname,email,phone,surl,furl,hash, nil] forKeys:[NSArray arrayWithObjects:#"txnid",#"key",#"amount",#"productinfo",#"firstname",#"email",#"phone",#"surl",#"furl",#"hash", nil]];
__block NSString *post = #"";
[parameters enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
if ([post isEqualToString:#""]) {
post = [NSString stringWithFormat:#"%#=%#",key,obj];
}else{
post = [NSString stringWithFormat:#"%#&%#=%#",post,key,obj];
}
}];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"https://test.payu.in/_payment"]]];
// change URL for live
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:postData];
[web_view_PayU loadRequest:request];
#define Merchant_Key #"your merchant key "
#define Salt #"your salt key"
#define Base_URL #"https://secure.payu.in"
> //this base url in case of origional payment key's if you want to integarate with
test key's write base Url can check in payumoney Faq
**
#define Success_URL #"https://www.google.co.in/"
#define Failure_URL #"http://www.bing.com/"
#define Product_Info #"Denim Jeans"
#define Paid_Amount #"1549.00"
#define Payee_Name #"Suraj Mirajkar"
-(void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:YES];
[self setTitle:#"Make A Payment"];
[self initPayment];
}
- (void)viewDidLoad {
[super viewDidLoad];
activityIndicatorView = [[UIActivityIndicatorView alloc] init];
activityIndicatorView.center = self.view.center;
[activityIndicatorView setColor:[UIColor blackColor]];
[self.view addSubview:activityIndicatorView];
}
-(void)initPayment {
int i = arc4random() % 9999999999;
NSString *strHash = [self createSHA512:[NSString stringWithFormat:#"%d%#",i,[NSDate date]]];// Generatehash512(rnd.ToString() + DateTime.Now);
NSString *txnid1 = [strHash substringToIndex:20];
strMIHPayID = txnid1;
NSString *key = Merchant_Key;
NSString *amount =[[NSUserDefaults standardUserDefaults]
stringForKey:#"orderprice"];
//NSString *amount = Paid_Amount;
NSString *productInfo = Product_Info;
NSString *firstname = Payee_Name;
NSString *email = [NSString stringWithFormat:#"suraj%d#yopmail.com",i];
//ADD A fake mail For Payment for testing purpose
// Generated a fake mail id for testing
NSString *phone = #"9762159571";
NSString *serviceprovider = #"payu_paisa";
NSString *hashValue = [NSString stringWithFormat:#"%#|%#|%#|%#|%#|%#|||||||||||%#",key,txnid1,amount,productInfo,firstname,email,Salt];
NSString *hash = [self createSHA512:hashValue];
NSDictionary *parameters = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:txnid1,key,amount,productInfo,firstname,email,phone,Success_URL,Failure_URL,hash,serviceprovider
, nil] forKeys:[NSArray arrayWithObjects:#"txnid",#"key",#"amount",#"productinfo",#"firstname",#"email",#"phone",#"surl",#"furl",#"hash",#"service_provider", nil]];
NSLog(#"%#",parameters);
__block NSString *post = #"";
[parameters enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
if ([post isEqualToString:#""]) {
post = [NSString stringWithFormat:#"%#=%#",key,obj];
} else {
post = [NSString stringWithFormat:#"%#&%#=%#",post,key,obj];
}
}];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#/_payment",Base_URL]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:postData];
[_webviewPaymentPage loadRequest:request];
[activityIndicatorView startAnimating];
}
-(NSString *)createSHA512:(NSString *)string {
const char *cstr = [string cStringUsingEncoding:NSUTF8StringEncoding];
NSData *data = [NSData dataWithBytes:cstr length:string.length];
uint8_t digest[CC_SHA512_DIGEST_LENGTH];
CC_SHA512(data.bytes, (CC_LONG)data.length, digest);
NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA512_DIGEST_LENGTH * 2];
for(int i = 0; i < CC_SHA512_DIGEST_LENGTH; i++) {
[output appendFormat:#"%02x", digest[i]];
}
return output;
}
#pragma UIWebView - Delegate Methods
-(void)webViewDidStartLoad:(UIWebView *)webView {
NSLog(#"WebView started loading");
}
-(void)webViewDidFinishLoad:(UIWebView *)webView {
[activityIndicatorView stopAnimating];
if (webView.isLoading) {
return;
}
NSURL *requestURL = [[_webviewPaymentPage request] URL];
NSLog(#"WebView finished loading with requestURL: %#",requestURL);
NSString *getStringFromUrl = [NSString stringWithFormat:#"%#",requestURL];
if ([self containsString:getStringFromUrl :Success_URL]) {
[self performSelector:#selector(delayedDidFinish:) withObject:getStringFromUrl afterDelay:0.0];
} else if ([self containsString:getStringFromUrl :Failure_URL]) {
// FAILURE ALERT
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Sorry !!!" message:#"Your transaction failed. Please try again!" delegate:self cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
alert.tag = 1;
[alert show];
}
}
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
[activityIndicatorView stopAnimating];
NSURL *requestURL = [[_webviewPaymentPage request] URL];
NSLog(#"WebView failed loading with requestURL: %# with error: %# & error code: %ld",requestURL, [error localizedDescription], (long)[error code]);
if (error.code == -1009 || error.code == -1003 || error.code == -1001) { //error.code == -999
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Oops !!!" message:#"Please check your internet connection!" delegate:self cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
alert.tag = 1;
[alert show];
}
}
- (void)delayedDidFinish:(NSString *)getStringFromUrl {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSMutableDictionary *mutDictTransactionDetails = [[NSMutableDictionary alloc] init];
[mutDictTransactionDetails setObject:strMIHPayID forKey:#"Transaction_ID"];
[mutDictTransactionDetails setObject:#"Success" forKey:#"Transaction_Status"];
[mutDictTransactionDetails setObject:Payee_Name forKey:#"Payee_Name"];
[mutDictTransactionDetails setObject:Product_Info forKey:#"Product_Info"];
[mutDictTransactionDetails setObject:Paid_Amount forKey:#"Paid_Amount"];
[self navigateToPaymentStatusScreen:mutDictTransactionDetails];
});
}
#pragma UIAlertView - Delegate Method
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if (alertView.tag == 1 && buttonIndex == 0) {
// Navigate to Payment Status Screen
NSMutableDictionary *mutDictTransactionDetails = [[NSMutableDictionary alloc] init];
[mutDictTransactionDetails setObject:Payee_Name forKey:#"Payee_Name"];
[mutDictTransactionDetails setObject:Product_Info forKey:#"Product_Info"];
[mutDictTransactionDetails setObject:Paid_Amount forKey:#"Paid_Amount"];
[mutDictTransactionDetails setObject:strMIHPayID forKey:#"Transaction_ID"];
[mutDictTransactionDetails setObject:#"Failed" forKey:#"Transaction_Status"];
[self navigateToPaymentStatusScreen:mutDictTransactionDetails];
}
}
- (BOOL)containsString: (NSString *)string : (NSString*)substring {
return [string rangeOfString:substring].location != NSNotFound;
}
- (void)navigateToPaymentStatusScreen: (NSMutableDictionary *)mutDictTransactionDetails {
dispatch_async(dispatch_get_main_queue(), ^{
PaymentStatusViewController *paymentStatusViewController = [[UIStoryboard storyboardWithName:#"Main" bundle:nil] instantiateViewControllerWithIdentifier:#"PaymentStatusScreenID"];
paymentStatusViewController.mutDictTransactionDetails = mutDictTransactionDetails;
[self.navigationController pushViewController:paymentStatusViewController animated:YES];
});
}
Important Note : you can check your Merchant key and Salt in seller Dashboard after Login ... Go To my account and check your merchant key and salt
Related
I am new in iOS and I am facing problem regarding to show events on calendar.I am using JTCalendar
https://github.com/chu888chu888/IOS-JTCalendar
My code is like this
In viewDidLoad
_calendarManager = [JTCalendarManager new];
_calendarManager.delegate = self;
// Generate random events sort by date using a dateformatter for the demonstration
//[self createRandomEvents];
// Create a min and max date for limit the calendar, optional
[self createMinAndMaxDate];
[_calendarManager setMenuView:_calendarMenuView];
[_calendarManager setContentView:_calendarContentView];
[_calendarManager setDate:_todayDate];
#pragma mark - CalendarManager delegate
// Exemple of implementation of prepareDayView method
// Used to customize the appearance of dayView
- (void)calendar:(JTCalendarManager *)calendar prepareDayView:(JTCalendarDayView *)dayView
{
// Today
if([_calendarManager.dateHelper date:[NSDate date] isTheSameDayThan:dayView.date]){
dayView.circleView.hidden = NO;
dayView.circleView.backgroundColor = [UIColor blueColor];
dayView.dotView.backgroundColor = [UIColor whiteColor];
dayView.textLabel.textColor = [UIColor whiteColor];
}
// Selected date
else if(_dateSelected && [_calendarManager.dateHelper date:_dateSelected isTheSameDayThan:dayView.date]){
dayView.circleView.hidden = NO;
dayView.circleView.backgroundColor = [UIColor redColor];
dayView.dotView.backgroundColor = [UIColor whiteColor];
dayView.textLabel.textColor = [UIColor whiteColor];
}
// Other month
else if(![_calendarManager.dateHelper date:_calendarContentView.date isTheSameMonthThan:dayView.date]){
dayView.circleView.hidden = YES;
dayView.dotView.backgroundColor = [UIColor redColor];
dayView.textLabel.textColor = [UIColor lightGrayColor];
}
// Another day of the current month
else{
dayView.circleView.hidden = YES;
dayView.dotView.backgroundColor = [UIColor redColor];
dayView.textLabel.textColor = [UIColor blackColor];
}
if([self haveEventForDay:dayView.date]){
dayView.dotView.hidden = NO;
}
else{
dayView.dotView.hidden = YES;
}
}
- (void)calendar:(JTCalendarManager *)calendar didTouchDayView:(JTCalendarDayView *)dayView
{
_dateSelected = dayView.date;
// Animation for the circleView
dayView.circleView.transform = CGAffineTransformScale(CGAffineTransformIdentity, 0.1, 0.1);
[UIView transitionWithView:dayView
duration:.3
options:0
animations:^{
dayView.circleView.transform = CGAffineTransformIdentity;
[_calendarManager reload];
} completion:nil];
// Don't change page in week mode because block the selection of days in first and last weeks of the month
if(_calendarManager.settings.weekModeEnabled){
return;
}
// Load the previous or next page if touch a day from another month
if(![_calendarManager.dateHelper date:_calendarContentView.date isTheSameMonthThan:dayView.date]){
if([_calendarContentView.date compare:dayView.date] == NSOrderedAscending){
[_calendarContentView loadNextPageWithAnimation];
}
else{
[_calendarContentView loadPreviousPageWithAnimation];
}
}
}
#pragma mark - CalendarManager delegate - Page mangement
// Used to limit the date for the calendar, optional
- (BOOL)calendar:(JTCalendarManager *)calendar canDisplayPageWithDate:(NSDate *)date
{
return [_calendarManager.dateHelper date:date isEqualOrAfter:_minDate andEqualOrBefore:_maxDate];
}
- (void)calendarDidLoadNextPage:(JTCalendarManager *)calendar
{
// NSLog(#"Next page loaded");
}
- (void)calendarDidLoadPreviousPage:(JTCalendarManager *)calendar
{
// NSLog(#"Previous page loaded");
}
#pragma mark - Fake data
- (void)createMinAndMaxDate
{
_todayDate = [NSDate date];
// Min date will be 2 month before today
_minDate = [_calendarManager.dateHelper addToDate:_todayDate months:-12];
// Max date will be 2 month after today
_maxDate = [_calendarManager.dateHelper addToDate:_todayDate months:12];
}
// Used only to have a key for _eventsByDate
- (NSDateFormatter *)dateFormatter
{
static NSDateFormatter *dateFormatter;
if(!dateFormatter){
dateFormatter = [NSDateFormatter new];
dateFormatter.dateFormat = #"dd-MM-yyyy";
}
return dateFormatter;
}
- (BOOL)haveEventForDay:(NSDate *)date
{
NSString *key = [[self dateFormatter] stringFromDate:date];
if(_eventsByDate[key] && [_eventsByDate[key] count] > 0){
return YES;
}
return NO;
}
//- (void)createRandomEvents
//{
// _eventsByDate = [NSMutableDictionary new];
//
// for(int i = 0; i < 30; ++i){
// // Generate 30 random dates between now and 60 days later
// NSDate *randomDate = [NSDate dateWithTimeInterval:(rand() % (3600 * 24 * 60)) sinceDate:[NSDate date]];
//
// // Use the date as key for eventsByDate
// NSString *key = [[self dateFormatter] stringFromDate:randomDate];
//
// if(!_eventsByDate[key]){
// _eventsByDate[key] = [NSMutableArray new];
// }
//
// [_eventsByDate[key] addObject:randomDate];
// }
//}
Its output is like this 02/06/2017 in array.How can I show it on calendar.
It is showing random events.But how can I show events on date?
Thanks in Advance!
Web Service
Getting value from 3 web service
#pragma mark - Schedule Audit Actitvity
//Connection Method and Delegate...
-(void)serverconnectionScheduleAudit{
[customActivityIndicator startAnimating];
int Auditid =[Empid intValue];
NSString *soapMessage = [NSString stringWithFormat:#"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
"<soap:Body>"
"<Get_Audits_Schedules_User xmlns=\"http://tempuri.org/\">"
"<UserId>%d</UserId>"
"</Get_Audits_Schedules_User>"
"</soap:Body>"
"</soap:Envelope>",Auditid];
NSURL *myNSUObj=[NSURL URLWithString:ServerString];
// NSURLRequest *myNSURequestObj=[NSURLRequest requestWithURL:myNSUObj];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:myNSUObj];
NSString *msgLength = [NSString stringWithFormat:#"%lu", (unsigned long)[soapMessage length]];
[theRequest addValue: #"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[theRequest addValue: #"http://tempuri.org/Get_Audits_Schedules_User" forHTTPHeaderField:#"SOAPAction"];
[theRequest addValue: msgLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPMethod:#"POST"];
[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
myNSUConnectionObjScheduleAudit=[[NSURLConnection alloc]initWithRequest:theRequest delegate:self];
NSLog(#"Data =%#",myNSUConnectionObjScheduleAudit);
if(myNSUConnectionObjScheduleAudit)
{
NSLog(#"successful connection");
myNSMDataFromServerScheduleAudit=[[NSMutableData alloc]init];
}
}
#pragma mark - Schedule Actitvity
//Connection Method and Delegate...
-(void)serverconnectionScheduleMeeting{
int KPI =[Empid intValue];
NSString *soapMessage = [NSString stringWithFormat:#"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
"<soap:Body>"
"<Get_Kpi_Schedules_User xmlns=\"http://tempuri.org/\">"
"<UserId>%d</UserId>"
"</Get_Kpi_Schedules_User>"
"</soap:Body>"
"</soap:Envelope>",KPI];
NSURL *myNSUObj=[NSURL URLWithString:ServerString];
// NSURLRequest *myNSURequestObj=[NSURLRequest requestWithURL:myNSUObj];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:myNSUObj];
NSString *msgLength = [NSString stringWithFormat:#"%lu", (unsigned long)[soapMessage length]];
[theRequest addValue: #"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[theRequest addValue: #"http://tempuri.org/Get_Kpi_Schedules_User" forHTTPHeaderField:#"SOAPAction"];
[theRequest addValue: msgLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPMethod:#"POST"];
[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
myNSUConnectionObjScheduleKPI=[[NSURLConnection alloc]initWithRequest:theRequest delegate:self];
NSLog(#"Data =%#",myNSUConnectionObjScheduleKPI);
if(myNSUConnectionObjScheduleKPI)
{
NSLog(#"successful connection");
myNSMDataFromServerScheduleKPI=[[NSMutableData alloc]init];
}
}
#pragma mark - Schedule Actitvity
//Connection Method and Delegate...
-(void)serverconnectionScheduleKPI{
int KPI =[Empid intValue];
NSString *soapMessage = [NSString stringWithFormat:#"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
"<soap:Body>"
"<Get_Meeting_Schedules_User xmlns=\"http://tempuri.org/\">"
"<UserId>%d</UserId>"
"</Get_Meeting_Schedules_User>"
"</soap:Body>"
"</soap:Envelope>",KPI];
NSURL *myNSUObj=[NSURL URLWithString:ServerString];
// NSURLRequest *myNSURequestObj=[NSURLRequest requestWithURL:myNSUObj];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:myNSUObj];
NSString *msgLength = [NSString stringWithFormat:#"%lu", (unsigned long)[soapMessage length]];
[theRequest addValue: #"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[theRequest addValue: #"http://tempuri.org/Get_Meeting_Schedules_User" forHTTPHeaderField:#"SOAPAction"];
[theRequest addValue: msgLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPMethod:#"POST"];
[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
myNSUConnectionObjScheduleMeeting=[[NSURLConnection alloc]initWithRequest:theRequest delegate:self];
NSLog(#"Data =%#",myNSUConnectionObjScheduleMeeting);
if(myNSUConnectionObjScheduleMeeting)
{
NSLog(#"successful connection");
myNSMDataFromServerScheduleMeeting=[[NSMutableData alloc]init];
}
}
#pragma mark - NSURLConnection Delegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
if(connection == myNSUConnectionObjScheduleAudit)
{
[myNSMDataFromServerScheduleAudit setLength:0];
}
if(connection == myNSUConnectionObjScheduleKPI)
{
[myNSMDataFromServerScheduleKPI setLength:0];
}
if(connection == myNSUConnectionObjScheduleMeeting)
{
[myNSMDataFromServerScheduleMeeting setLength:0];
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
if(connection == myNSUConnectionObjScheduleAudit)
{
[myNSMDataFromServerScheduleAudit appendData:data];
}
if(connection == myNSUConnectionObjScheduleKPI)
{
[myNSMDataFromServerScheduleKPI appendData:data];
}
if(connection == myNSUConnectionObjScheduleMeeting)
{
[myNSMDataFromServerScheduleMeeting appendData:data];
}
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
if(connection == myNSUConnectionObjScheduleAudit)
{
loginStatusScheduleAudit = [[NSString alloc] initWithBytes: [myNSMDataFromServerScheduleAudit mutableBytes] length:[myNSMDataFromServerScheduleAudit length] encoding:NSUTF8StringEncoding];
NSLog(#"loginStatus =%#",loginStatusScheduleAudit);
NSError *parseError = nil;
NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLString:loginStatusScheduleAudit error:&parseError];
NSLog(#"JSON DICTIONARY = %#",xmlDictionary);
recordResultScheduleAudit = [xmlDictionary[#"success"] integerValue];
NSLog(#"Success: %ld",(long)recordResultScheduleAudit);
NSDictionary* Address=[xmlDictionary objectForKey:#"soap:Envelope"];
NSLog(#"Address Dict = %#",Address);
NSDictionary *new =[Address objectForKey:#"soap:Body"];
NSLog(#"NEW DICT =%#",new);
NSDictionary *LoginResponse=[new objectForKey:#"Get_Audits_Schedules_UserResponse"];
NSLog(#"Login Response DICT =%#",LoginResponse);
NSDictionary *LoginResult=[LoginResponse objectForKey:#"Get_Audits_Schedules_UserResult"];
NSLog(#"Login Result =%#",LoginResult);
if(LoginResult.count>0)
{
NSLog(#"Login Result = %#",LoginResult);
NSLog(#"Login Result Dict =%#",LoginResult);
NSString *teststr =[[NSString alloc] init];
teststr =[LoginResult objectForKey:#"text"];
NSLog(#"Test String Value =%#",teststr);
NSString *string = [LoginResult valueForKey:#"text"];
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
responsedictScheduleAudit = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
EndDatearrayScheduleAudit =[[NSMutableArray alloc] init];
EndDatearrayScheduleAudit=[responsedictScheduleAudit valueForKey:#"EndDate"];
}
}
if(connection == myNSUConnectionObjScheduleKPI)
{
loginStatusScheduleKPI = [[NSString alloc] initWithBytes: [myNSMDataFromServerScheduleKPI mutableBytes] length:[myNSMDataFromServerScheduleKPI length] encoding:NSUTF8StringEncoding];
NSLog(#"loginStatus =%#",loginStatusScheduleKPI);
NSError *parseError = nil;
NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLString:loginStatusScheduleKPI error:&parseError];
NSLog(#"JSON DICTIONARY = %#",xmlDictionary);
recordResultScheduleKPI = [xmlDictionary[#"success"] integerValue];
NSLog(#"Success: %ld",(long)recordResultScheduleKPI);
NSDictionary* Address=[xmlDictionary objectForKey:#"soap:Envelope"];
NSLog(#"Address Dict = %#",Address);
NSDictionary *new =[Address objectForKey:#"soap:Body"];
NSLog(#"NEW DICT =%#",new);
NSDictionary *LoginResponse=[new objectForKey:#"Get_Kpi_Schedules_UserResponse"];
NSLog(#"Login Response DICT =%#",LoginResponse);
NSDictionary *LoginResult=[LoginResponse objectForKey:#"Get_Kpi_Schedules_UserResult"];
NSLog(#"Login Result =%#",LoginResult);
if(LoginResult.count>0)
{
NSLog(#"Login Result = %#",LoginResult);
NSLog(#"Login Result Dict =%#",LoginResult);
NSString *teststr =[[NSString alloc] init];
teststr =[LoginResult objectForKey:#"text"];
NSLog(#"Test String Value =%#",teststr);
NSString *string = [LoginResult valueForKey:#"text"];
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
responsedictScheduleKPI = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
EndDatearrayScheduleKPI =[[NSMutableArray alloc] init];
EndDatearrayScheduleKPI =[responsedictScheduleKPI valueForKey:#"EndDate"];
}
}
if(connection == myNSUConnectionObjScheduleMeeting)
{
loginStatusScheduleMeeting = [[NSString alloc] initWithBytes: [myNSMDataFromServerScheduleMeeting mutableBytes] length:[myNSMDataFromServerScheduleMeeting length] encoding:NSUTF8StringEncoding];
NSLog(#"loginStatus =%#",loginStatusScheduleMeeting);
NSError *parseError = nil;
NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLString:loginStatusScheduleMeeting error:&parseError];
NSLog(#"JSON DICTIONARY = %#",xmlDictionary);
recordResultScheduleMeeting = [xmlDictionary[#"success"] integerValue];
NSLog(#"Success: %ld",(long)recordResultScheduleMeeting);
NSDictionary* AddressDict=[xmlDictionary objectForKey:#"soap:Envelope"];
NSLog(#"Address Dict = %#",AddressDict);
NSDictionary *new =[AddressDict objectForKey:#"soap:Body"];
NSLog(#"NEW DICT =%#",new);
NSDictionary *LoginResponse=[new objectForKey:#"Get_Meeting_Schedules_UserResponse"];
NSLog(#"Login Response DICT =%#",LoginResponse);
NSDictionary *LoginResult=[LoginResponse objectForKey:#"Get_Meeting_Schedules_UserResult"];
NSLog(#"Login Result =%#",LoginResult);
if(LoginResult.count>0)
{
NSLog(#"Login Result = %#",LoginResult);
NSLog(#"Login Result Dict =%#",LoginResult);
NSString *teststr =[[NSString alloc] init];
teststr =[LoginResult objectForKey:#"text"];
NSLog(#"Test String Value =%#",teststr);
NSString *string = [LoginResult valueForKey:#"text"];
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
responsedictScheduleMeeting = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
EndDatearrayScheduleMeeting =[[NSMutableArray alloc] init];
EndDatearrayScheduleMeeting =[responsedictScheduleMeeting valueForKey:#"EndDate"];
}
}
[customActivityIndicator stopAnimating];
}
#pragma mark - NSXMLParsing Delegate
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
if([elementName isEqualToString:#"FillBlocksNew"])
{
myDataClassObjScheduleAudit=[[mydata alloc]init];
}
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
myMutableStringObjScheduleAudit=[[NSMutableString alloc]initWithString:string];
NSLog(#"Array String: %#",myMutableStringObjScheduleAudit);
NSData *dataAudit = [myMutableStringObjScheduleAudit dataUsingEncoding:NSUTF8StringEncoding];
responsedictScheduleAudit = [NSJSONSerialization JSONObjectWithData:dataAudit options:0 error:nil];
NSLog(#"JSON DATA = %#",responsedictScheduleAudit);
myMutableStringObjScheduleKPI=[[NSMutableString alloc]initWithString:string];
NSLog(#"Array String: %#",myMutableStringObjScheduleKPI);
NSData *dataKPI = [myMutableStringObjScheduleKPI dataUsingEncoding:NSUTF8StringEncoding];
responsedictScheduleKPI = [NSJSONSerialization JSONObjectWithData:dataKPI options:0 error:nil];
NSLog(#"JSON DATA = %#",responsedictScheduleKPI);
myMutableStringObjScheduleMeeting=[[NSMutableString alloc]initWithString:string];
NSLog(#"Array String: %#",myMutableStringObjScheduleMeeting);
NSData *dataMeeting = [myMutableStringObjScheduleMeeting dataUsingEncoding:NSUTF8StringEncoding];
responsedictScheduleMeeting = [NSJSONSerialization JSONObjectWithData:dataMeeting options:0 error:nil];
NSLog(#"JSON DATA = %#",responsedictScheduleMeeting);
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
NSLog(#"DataArray: %#",myDataNSMArrayScheduleAudit);
}
You have commented function "createRandomEvents" in your source code.
This function defines your dates to be displayed on calendar.
Get events data from web service and you have to add dates in array "eventsByDate". Then you should be able to view dates.
Code:
- (void)viewDidLoad {
[super viewDidLoad];
NSMutableArray *arrDates = [[NSMutableArray alloc] init];
}
In ScheduleKPI API response
[arrDates addObjectsFromArray:EndDatearrayScheduleKPI];
In ScheduleAudit API response
[arrDates addObjectsFromArray:EndDatearrayScheduleAudit];
In ScheduleMeeting API response
[arrDates addObjectsFromArray:EndDatearrayScheduleMeeting];
[self funAddEvents:arrDates];
- (void)funAddEvents:(NSArray *)arrDate
{
eventsByDate = [NSMutableDictionary new];
for(NSString *strDate in arrDate){
NSDateFormatter *dateformat = [[NSDateFormatter alloc] init];
[dateformat setDateFormat:#"YYYY/MM/dd"];
NSDate *myDate = [dateformat dateFromString:strDate];
NSString *key = [[self dateFormatter] stringFromDate:myDate];
if(!eventsByDate[key]){
eventsByDate[key] = [NSMutableArray new];
}
[eventsByDate[key] addObject:myDate];
}
[self.calendar reloadData];
}
This question already has an answer here:
Storing values in completionHandlers - Swift
(1 answer)
Closed 7 years ago.
I have a function that get data from server and it will run asynchronous while other function is running.
my problem, i called the function [self getdata] at viewdidload(). and NSLog at below the called function but the data is delay. it get null. may i know anyway to wait the function run finish only print out the data for me?
-(void)getdata
{
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *userID = [prefs objectForKey:#"userID"];
//get merged news
float latitude = [[prefs objectForKey:LAST_KNOWN_LATITUDE] floatValue];
float longitude = [[prefs objectForKey:LAST_KNOWN_LONGITUDE] floatValue];
NSInteger ref_id =[[[eventDict objectForKey:#"id"] substringFromIndex:2]integerValue];
NSInteger reference_EventType = [[eventDict objectForKey:#"type_id"]integerValue];
NSString *type =#"EVENT";
NSString *str = [NSString stringWithFormat:#"%#event.php", API_URL];
NSURL *URL = [NSURL URLWithString:str];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:URL];
__unsafe_unretained ASIFormDataRequest *_request = request;
[request setRequestMethod:#"POST"];
[request setPostValue:#"get_event_notification" forKey:#"tag"];
[request setPostValue:[NSNumber numberWithInteger:ref_id] forKey:#"reference_id"];
[request setPostValue:[NSNumber numberWithInteger:reference_EventType] forKey:#"reference_eventType"];
[request setPostValue:type forKey:#"reference_type"];
[request setPostValue:[NSNumber numberWithFloat:latitude] forKey:#"latitude"];
[request setPostValue:[NSNumber numberWithFloat:longitude] forKey:#"longitude"];
[request setPostValue:userID forKey:#"user_id"];
[request setDelegate:self];
[request setTimeOutSeconds:30.0];
[request setShouldAttemptPersistentConnection:NO];
[request startAsynchronous];
[request setCompletionBlock:^(void){
NSInteger responseCode = [_request responseStatusCode];
if (responseCode == 200 || responseCode == 201 || responseCode == 202)
{
//NSLog(#"%#", [_request responseString]);
NSMutableDictionary *response = (NSMutableDictionary *)[[_request responseString] JSONValue];
NSInteger success = [[response objectForKey:#"success"] integerValue];
if (success == 1)
{
if ([[response objectForKey:#"event"] isKindOfClass:[NSArray class]]) {
event = [[response objectForKey:#"event"] objectAtIndex:0];
dataArray=[event objectForKey:#"merged"];
NSLog(#"dataArray %d",dataArray.count);
mergedCount=[NSString stringWithFormat:#"%d",dataArray.count];
NSArray *pathsMergedCount = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryMergedCount = [pathsMergedCount objectAtIndex:0];
NSString *filePathMergedCount= [documentsDirectoryMergedCount stringByAppendingPathComponent:#"fileMergedCount.txt"];
[mergedCount writeToFile:filePathMergedCount atomically:TRUE encoding:NSUTF8StringEncoding error:NULL];
for(i=0;i<[dataArray count];i++)
{
feedDict=[dataArray objectAtIndex:i];
[eventIDMerged addObject:[feedDict objectForKey:#"event_id"]];
[eventDescMerged addObject:[feedDict objectForKey:#"description"]];
}
}}}
}];
[request setFailedBlock:^(void){
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Connection Failed" message:#"Internet connection too slow, please ensure you have a strong internet connection to have better user experience" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
}];
}
-(void)viewDidLoad
{
[self getdata];
dispatch_async(dispatch_get_main_queue(), ^{
NSArray *pathsMergedCount = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryMergedCount = [pathsMergedCount objectAtIndex:0];
NSString *filePathMergedCount= [documentsDirectoryMergedCount stringByAppendingPathComponent:#"fileMergedCount.txt"];
NSString *strMergedCount = [NSString stringWithContentsOfFile:filePathMergedCount encoding:NSUTF8StringEncoding error:NULL];
NSLog(#"Count3m %#",strMergedCount);
});
});
}
See my answer in this thread:
Storing values in completionHandlers - Swift
It includes a link to a full project (in Swift) demonstrating using completion handlers to manage async tasks.
I have integrated google plus in my ios app ,I am able to get access token.I have used authentication flow to integrate google plus.So now after getting access token how can i get user profile details like username, email id, profile pic etc?
My code to get access token is as below:
-(IBAction)btnGooglePlusClicked:(UIButton *)sender
{
IBwebView.hidden = FALSE;
NSString *url = [NSString stringWithFormat:#"https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=%#&redirect_uri=%#&scope=%#&data-requestvisibleactions=%#",GOOGLE_PLUS_CLIENT_ID,GOOGLE_PLUS_CALL_BACK_URL,GOOGLE_PLUS_SCOPE,GOOGLE_PLUS_VISIBLE_ACTIONS];
[IBwebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
}
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
// [indicator startAnimating];
if ([[[request URL] host] isEqualToString:#"localhost"]) {
// Extract oauth_verifier from URL query
NSString* verifier = nil;
NSArray* urlParams = [[[request URL] query] componentsSeparatedByString:#"&"];
for (NSString* param in urlParams) {
NSArray* keyValue = [param componentsSeparatedByString:#"="];
NSString* key = [keyValue objectAtIndex:0];
if ([key isEqualToString:#"code"]) {
verifier = [keyValue objectAtIndex:1];
NSLog(#"verifier %#",verifier);
break;
}
}
if (verifier) {
NSString *data = [NSString stringWithFormat:#"code=%#&client_id=%#&client_secret=%#&redirect_uri=%#&grant_type=authorization_code", verifier,GOOGLE_PLUS_CLIENT_ID,GOOGLE_PLUS_CLIENT_SECRET,GOOGLE_PLUS_CALL_BACK_URL];
NSString *url = [NSString stringWithFormat:#"https://accounts.google.com/o/oauth2/token"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[data dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
receivedData = [[NSMutableData alloc] init];
} else {
// ERROR!
}
[webView removeFromSuperview];
return NO;
}
return YES;
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[receivedData appendData:data];
NSLog(#"verifier %#",receivedData);
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:[NSString stringWithFormat:#"%#", error]
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *response = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
SBJsonParser *jResponse = [[SBJsonParser alloc]init];
NSDictionary *tokenData = [jResponse objectWithString:response];
// WebServiceSocket *dconnection = [[WebServiceSocket alloc] init];
// dconnection.delegate = self;
NSString *pdata = [NSString stringWithFormat:#"type=3&token=%#&secret=123&login=%#", [tokenData objectForKey:#"refresh_token"], self.isLogin];
// NSString *pdata = [NSString stringWithFormat:#"type=3&token=%#&secret=123&login=%#",[tokenData accessToken.secret,self.isLogin];
// [dconnection fetch:1 withPostdata:pdata withGetData:#"" isSilent:NO];
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:#"Google Access TOken"
message:pdata
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
I feel the the method you are using will not help to get the profile detail.
I suggest to use the proper method which ensures the best results.
Please check this out : https://developers.google.com/+/mobile/ios/
This will surely help you to get required outcome.
I know that there are plenty of questions that have been asked and answered and non of them pertain to my problem.
I am posting XML to a server and I get a response back. My problem is getting a specified key back from the response.
I am trying to list all Genders e.g Male, Female and their id's however when parsing the XML into text with NSXML I only get back the Female and ID 2 and I do not get back Male?
I have researched and tried to fix this issue but to no avail.
here is my code:
- (void)getGender {
NSString *soapMessage = [NSString stringWithFormat:
#"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:app=\"http://app.ws.api.bells.wigroup.com/\">"
"<soap:Header/>\n"
"<soap:Body>\n"
"<app:getAllGenders>\n"
"<request>\n"
"<apiCredentials>\n"
"<apiId>IPHONE_APP</apiId>\n"
"<sha1Password>8656cafcd71cbbfe773a0fdb6c422666a80e5b8f</sha1Password>\n"
"</apiCredentials>\n"
"<request>\n"
"</request>\n"
"</request>\n"
"</app:getAllGenders>\n"
"</soap:Body>\n"
"</soap:Envelope>\n"
];
NSLog(#"Message%#",soapMessage);
NSURL *url = [NSURL URLWithString:#"http://qa.wigroup.co:8080/bells/AppWS"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:#"%d", [soapMessage length]];
[theRequest addValue: #"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
//[theRequest addValue: #"http://" forHTTPHeaderField:#"SOAPAction"];
[theRequest addValue: msgLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPMethod:#"POST"];
[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if( theConnection )
{
NSURLResponse *response;
NSError *error;
NSData *urlData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response error:&error];
NSString *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"Login response XML:%#",str);
// create and init NSXMLParser object
XmlArrayParser *parser = [[XmlArrayParser alloc] initWithData:urlData];
parser.rowElementName = #"return";
parser.elementNames = [NSArray arrayWithObjects:#"response", #"responseCode", #"responseDesc", #"gendersList", nil];
parser.attributeNames = [NSArray arrayWithObjects:#"id", #"gender", nil];
if ([parser.rowElementName isEqualToString:#"responseCode"] && _flag)
{
//read the value here
NSLog(#"flagging");
}
// parsing...
BOOL success = [parser parse];
// test the result
if (success)
{
NSMutableArray *loginAuth = [parser items];
// self.textView.text = [NSString stringWithFormat:
// #"This is an array of dictionaries, one dictionary for each user:\n\n%#",
// [users description]];
// NSDictionary *eventLocation = [NSDictionary dictionaryWithObjectsAndKeys:#"response", nil];
NSDictionary *loginResponse = [loginAuth objectAtIndex:0]; // this retrieves the first user
NSString *userResponse = loginResponse[#"gendersList"]; // this retrieves that user's username in Xcode 4.5 and greater
NSString *userRes = [loginResponse objectForKey:#"id"];
NSString *test = [loginAuth description];
NSLog(#"Returned Code loginResponse %#",loginResponse);
NSLog(#"Returned Code userResponse %# %#",userResponse, userRes);
NSLog(#"Returned Code test %#",test);
NSMutableArray *array=[[NSMutableArray alloc]initWithCapacity:10];
for (NSDictionary *defineXMLData in loginAuth) {
NSNumber * responseCode = [defineXMLData objectForKey:#"responseCode"];
NSArray * responseDEsc = [defineXMLData objectForKey:#"responseDesc"];
NSArray * genderList = [defineXMLData objectForKey:#"gendersList"];
// NSArray * gender = [defineJsonData objectForKey:#"gender"];
NSLog(#"Genders%#", genderList);
[array addObject: responseCode];
[array addObject: responseDEsc];
[array addObject: genderList];
//[array addObject: gender];
// [array addObject: vouchersUser];
}
label.numberOfLines = 2000; // for example
label.lineBreakMode = NSLineBreakByClipping;
NSString *output=[array componentsJoinedByString:#","];
label.text = [NSString stringWithFormat:#"XML Result: %# ",output];
[SVProgressHUD dismiss];
// [[[UIAlertView alloc] initWithTitle:nil
// message:[NSString stringWithFormat:#"No errors - user count : %i", [[parser items] count]]
// delegate:nil
// cancelButtonTitle:#"OK"
// otherButtonTitles:nil] show];
}
else
{
NSLog(#"Error parsing document!");
// [[[UIAlertView alloc] initWithTitle:nil
// message:#"Error parsing document!"
// delegate:nil
// cancelButtonTitle:#"OK"
// otherButtonTitles:nil] show];
}
}
else
{
NSLog(#"theConnection is NULL");
}
NSLog(#"test");
}
And the XML I get back from my nslog:
<?xml version="1.0" encoding="UTF-8"?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Body>
<ns2:getAllGendersResponse xmlns:ns2="http://app.ws.api.bells.wigroup.com/">
<return>
<responseCode>-1</responseCode>
<responseDesc>Success</responseDesc>
<response>
<responseCode>-1</responseCode>
<responseDesc>Success</responseDesc>
<gendersList>
<gender>Male</gender>
<id>1</id>
</gendersList>
<gendersList>
<gender>Female</gender>
<id>2</id>
</gendersList>
</response>
Is only parsing:
{
gendersList = Female2;
responseCode = "-1";
responseDesc = Success;
}
You have not correctly pointed the problem. Your code parses the whole document, but you keep only the last items (last genderList, last responseCode, last responseDesc). Initialize an array and in your for loop add each dictionary to that array when parsed.
I get four parameters from a web service (web service 2 in my flow) - slno, order, flag, name. I don't know how many times these parameters are going to be received. Out of these four paramters, I send 'name' to a label as it contains questions to be asked.
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"some url"]];
NSLog(#"Web service 2 url is = %#", url);
NSString *json = [NSString stringWithContentsOfURL:url encoding:NSASCIIStringEncoding error:&error];
NSLog(#"Json data = %# \n error = %#", json, error);
if(!error)
{
NSData *jsonData = [json dataUsingEncoding:NSASCIIStringEncoding];
NSArray *myJsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:Nil];
//NSArray *arrayLabel = [[NSArray alloc] initWithObjects:label1, label2, label3, label4, label5, label6, nil];
//NSMutableArray *tempArray = [NSMutableArray arrayWithCapacity:myJsonArray.count];
i = 0;
for(NSDictionary *myJsonDictionary in myJsonArray)
{
//UILabel *label = (UILabel *)[arrayLabel objectAtIndex:i++];
//[label setText:myJsonDictionary[#"Name"]];
NSString *name = myJsonDictionary[#"Name"];
NSLog(#"Question from ws2 is %#", name);
projectIdGobal = myJsonDictionary[#"ProjectID"];
NSLog(#"Project id from ws2 is %#", projectIdGobal);
slno = myJsonDictionary[#"SLNO"];
NSLog(#"slno from ws2 is %#", slno);
NSString *idWS2 = myJsonDictionary[#"ID"];
NSLog(#"id from ws2 is %#", idWS2);
order = myJsonDictionary[#"Order"];
NSLog(#"order from ws2 is %#", order);
flag = myJsonDictionary[#"Flag"];
NSLog(#"flag from ws2 is %#", flag);
[self putLabelsInScrollView:name];
i++;
}
NSLog(#"Number of cycles in for-each = %d", i);
[activity stopAnimating];
}
- (void) putLabelsInScrollView:(NSString *)labelText
{
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, yPosition_label, 261, 30)];
[label setFont:[UIFont fontWithName:#"Helvetica Neue" size:12.0f]];
label.numberOfLines = 2;
[label setText:labelText];
[self.scroll addSubview:label];
yPosition_label += 90;
UITextField *text = [[UITextField alloc] initWithFrame:CGRectMake(10, yPosition_text, 261, 30)];
text.borderStyle = UITextBorderStyleRoundedRect;
text.textColor = [UIColor blackColor];
text.font = [UIFont systemFontOfSize:12.0];
text.backgroundColor = [UIColor clearColor];
text.keyboardType = UIKeyboardTypeDefault;
text.delegate = self;
[self.scroll addSubview:text];
yPosition_text += 90;
yPosition_result = yPosition_label + yPosition_text;
[self.scroll setContentSize:CGSizeMake(self.scroll.frame.size.width, yPosition_result)];
[self.view addSubview:self.scroll];
}
Now I created a dynamically created text fields and stored the answers entered by the user in the array as follows.
- (IBAction)save:(id)sender {
NSMutableArray *mutableTextArray = [[NSMutableArray alloc] init];
for(UITextField *field in self.scroll.subviews)
{
if([field isKindOfClass:[UITextField class]])
{
if([[field text] length] > 0)
{
[mutableTextArray addObject:field.text];
//NSLog(#"Save button 1 : %#", mutableTextArray);
//NSString *str = [str stringByAppendingString:[mutableTextArray objectAtIndex:0]];
//[self fetchStrings:mutableTextArray];
}
}
}
NSLog(#"Save button 2 : %#", mutableTextArray);
[self fetchStrings:mutableTextArray];
}
Now while posting the answer to another web service (web service 3 in my flow), I must pass slno, order, flag i get from web service 2 and the 'answer' that the user enters in the dynamically created field to the 'answer' key. How shall I get these 4 parameters [slno, order, flag (from web service 2) and answer (from dynamic text field)] to post to web service 3?
- (void) fetchStrings:(NSArray *)textArray
{
NSLog(#"Array string = %#", textArray); //I get the array that the user enters in the dynamically created text field here
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
NSUserDefaults *getDefaults = [NSUserDefaults standardUserDefaults];
NSString *uidObject = [getDefaults objectForKey:#"UIDKEY"];
NSString *str = [NSString stringWithFormat:#"{\"ProjID\": \"%#\",\"Uid\": \"%#\",\"EmailID\": \"%#\",", projectIdGobal, uidObject, emailFromLogin];
str = [str stringByAppendingString:#"\"ProjectInviterFQAnswers\": ["];
**for (SaveAsking *saveAsk in textArray) {
str = [str stringByAppendingString:[NSString stringWithFormat:#"{\"slno\":\"%#\",\"Answer\": \"%#\",\"order\": \"%#\", \"flag\": \"%#\"},", saveAsk.slno, saveAsk.answer, saveAsk.order, saveAsk.flag]]; // I want to save the parameters here
}**
// SaveAsking is a nsobject class where I have used a self created delegate for slno answer order and flag
str = [str stringByAppendingString:#"]}"];
NSLog(#"String is === %#", str);
NSURL *url = [NSURL URLWithString:#"some url"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
NSData *requestData = [str dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
if(error || !data)
{
NSLog(#"JSON Data not posted!");
[activity stopAnimating];
UIAlertView *alertMessage = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Data not saved" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertMessage show];
}
else
{
[activity startAnimating];
NSLog(#"JSON data posted! :)");
NSError *error = Nil;
NSJSONSerialization *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
NSLog(#"Response is %#", jsonObject);
}
}];
}
Please do correct my flow if you understood what am i trying to achieve. Number for iterations in left box == number of iterations in right box and the result is in the middle box which needs to be posted to web service.
Try keeping a dictionary of the requests, where the key would be the dynamically created UITextField, and the value would be another dictionary with the values that you need to send.
So , when you create the textField, after adding it to the subview, create a dictionary with your values (sino, order, flag), and set that dictionary to the textfield.
When you are ready to send the data, you'll have a direct connection between the textField and the values for your webservice3.