1

I have tried to find a similar question but I was unable to do so. I have a singleton that is used to gather information through out my app. Once of the values is obtained within the following method.

-(NSString *)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data-(NSString *)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

In this method I get the response from th webservice that I am trying to connect to. Everything is good. However any attempt to save the variable value to my singleton fails. Within this method no problem. When I try to get to the next view and reference my singleton, it is as if the value never gets saved.

Here is a skeleton of my code.

NBXJSONResponse *jsonResponse = [NBXJSONResponse sharedHostedResponseSingleton];
[jsonResponse setHostedURL:_hostedURL];

Basically the goal here is to have the hosted payment page appear in the next view. The flow flow for that works. I just need to pass the URI link so that payment can be made.

I know that I can return a value from this delegate method, but since I never explicitly call this method, so I am unsure where it is being called. Probably the reason why my values are not being saved in the singleton class.

EDIT:

Right now I have one view which does all of the action.

//
//  NBXViewController.h file

#import <UIKit/UIKit.h>

@interface NBXViewController : UIViewController

//*************************************************
// Variables to be declared for NBXViewController *
//*************************************************

@property (strong, nonatomic) IBOutlet UILabel *storeLabel;
@property (strong, nonatomic) IBOutlet UIButton *purchaseButton;
@property (strong, nonatomic) IBOutlet NSString *hostedURL;


//*************************************************
// Button Action methods for the buttons on View  *
//*************************************************

- (IBAction)puchaseButtonAction:(id)sender;

//*************************************************
// Connection Delegate Methods                    *
//*************************************************

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error; // Handle Connection Error
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data; // Data Received from Connection (Header Information)
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response; //Response from Connection (Return from Hosted being called)
-(void)connectionDidFinishLoading:(NSURLConnection *)connection; // Coonection did finish loading


@end

Implementation file.

//
//  NBXViewController.m
//  HostedAPI
//
//  Created by Philip Teoli on 3/1/2014.
//  Copyright (c) 2014 Philip Teoli. All rights reserved.
//

#import "NBXViewController.h"
#import "NBXJSONResponse.h"


@interface NBXViewController ()

@end

@implementation NBXViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//****************************************
// PurchaseButton Action Method          *
//****************************************

- (IBAction)puchaseButtonAction:(id)sender
{
    //************************************
    // Building JSON Request             *
    //************************************

    NSString *jsonString = @"Sample Request";

    //**************************************
    // Convert JSON String to NSData       *
    //**************************************

    NSData* jsonRequestData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];

    //**************************************
    // Creating JSON object to Send        *
    //**************************************

    NSString *jsonRequest = [[NSString alloc] initWithData:jsonRequestData encoding:NSUTF8StringEncoding];


    //*****************************************
    // Base64 Encoding for Application Header *
    //*****************************************

    NSString *base64Signature = @"NbMIIkomZ8mFNw97EGRT:NAA5e965731e8a27ab11f5f";
    NSString *basic = @"Basic: ";
    NSData *base64SignatureData = [base64Signature dataUsingEncoding: NSUTF8StringEncoding];
    NSString *base64SignatureEncoded = [base64SignatureData base64EncodedStringWithOptions:0];
    NSString *header = nil;
    header = [basic stringByAppendingString:base64SignatureEncoded];

   // NSLog(@"Encoded Header: %@", header);

    //*************************************
    // Preparing to send XML through POST *
    //*************************************

    NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[jsonRequest length]]; //Calculating the Content Length
    NSData *postData = [jsonRequest dataUsingEncoding:NSUTF8StringEncoding]; // preapring JSON Request to be sent


    //**************************************
    // Headers and POST Body               *
    //**************************************

    NSURL *serviceUrl = [NSURL URLWithString:@"https://pay.test.ewbservice.com/orders"];
    NSMutableURLRequest *serviceRequest=[NSMutableURLRequest requestWithURL:serviceUrl cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60];
    [serviceRequest setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [serviceRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [serviceRequest setValue:header forHTTPHeaderField:@"Authorization"];
    [serviceRequest setHTTPMethod:@"POST"];
    [serviceRequest setHTTPBody:postData];

    NSURLConnection *connection = [[NSURLConnection alloc]
                                   initWithRequest:serviceRequest
                                   delegate:self startImmediately:YES];

    [connection scheduleInRunLoop:[NSRunLoop mainRunLoop]
                          forMode:NSDefaultRunLoopMode];
    [connection start];

    NSLog(@"Hosted URL in Button: %@", _hostedURL);



}

//****************************************************
// Implementation of Connection Delegate Methods     *
//****************************************************


-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"did fail");
}

//*******************************************************
// Connection Data Received                             *
//*******************************************************

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    NSString *dataResponse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSError *error = nil;
    NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData: [dataResponse dataUsingEncoding:NSUTF8StringEncoding]
                                    options: NSJSONReadingMutableContainers
                                      error: &error];

    //********************************
    // Iterating through Dictionary  *
    //********************************

    NSArray *jsonLink = nil;

    for(id key in jsonDictionary)
    {
        if ([key isEqualToString:@"link"])
        {
            jsonLink = [jsonDictionary objectForKey:key]; // this returns a dictionary. Will need to parse dictionary another 2 times to get proper URI.
        }

    }

    NSDictionary *test = [jsonLink objectAtIndex:0];


    for(id key in test)
    {
        if ([key isEqualToString:@"uri"])
        {
            _hostedURL = [test objectForKey:key];
        }

    }

    NBXJSONResponse *jsonResponse = [NBXJSONResponse sharedHostedResponseSingleton];
    [jsonResponse setHostedURL:_hostedURL];
}

//*******************************************************
// Connection Response Method                           *
//*******************************************************

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"did receive response: \n %@", response);
    NBXJSONResponse *jsonResponse = [NBXJSONResponse sharedHostedResponseSingleton];
    [jsonResponse setHostedURL:_hostedURL];

}

//*******************************************************
// Connection Finished Loading Data Method              *
//*******************************************************

-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"did finish loading!!! \n%@", _hostedURL);
  //  NBXJSONResponse *jsonResponse = [NBXJSONResponse sharedHostedResponseSingleton];
  //  [jsonResponse setHostedURL:_hostedURL];
}


@end

Please let me know of your thoughts. I can post more details if needed. Thanks in advance for your help!!!

Regards,

  • It's not clear from your question where those bits of code are. You should specify what code is in which controller (or singleton). Also, normally, you get the data from connectionDidFinishLoading:, not from didReceiveData (since that method can be called multiple times if the data arrives in pieces). – rdelmar Mar 09 '14 at 04:45
  • Sorry if my question was not clear. I will try to make it a little clearer. I will be honest, I never did use the connectionDidFinishLoading to get the responses cause everything that I needed was in the didReceiveData method. As for the Singleton, I use it throughout my application. No matter where I call my singleton in this view, No value gets saved to it from the didReceiveData. However if I save data from anywhere else in the view, there is no issue. I do understand about having the responses in pieces but in this case it is not applicable. – Corporate One Mar 09 '14 at 15:04
  • The responses are Synchronous and the response data gets sent in one shot. I will try and use the didFinishLoading method and if here I have any more luck. Thanks for the pointers. – Corporate One Mar 09 '14 at 15:05
  • I have just tried to save a value manually from the connectionDidFinishLoading and the same result. Any variable saved cannot be used outside of these delagate methods. In my case trying to save the value to a singleton class. – Corporate One Mar 09 '14 at 16:06
  • You certainly should be able to save a value outside the delegate methods, but I still can't tell what you're doing. Post the entire connectionDidFinishLoading method. Also, I still can't tell where some of the code snippets you posted are in the context of your app. You need to show complete methods and state which controller the code is in. Also, initWithRequest:delegate:startImmediately: starts on its own -- you shouldn't add it to a run loop or call start. – rdelmar Mar 10 '14 at 01:11
  • Hi,I will get more code and explanations up as soon as I can. However I had tried without the Loop and it did not run. That is the reason why I had added it. – Corporate One Mar 10 '14 at 18:36
  • @rdelmar I have added my .h and .m files. The code is not fully correct. I am just trying to do a simple task right now of getting my variables to be saved outside of the delegate methods for connection.I know that the memory management is nto great right now and that I could do things differently .I am just looking for a simple solution for this issue that I am having. – Corporate One Mar 10 '14 at 23:48
  • So I'm a little unsure what your problem is. You're trying to pass _hostedURL to your singleton, right? I assume that it logs correctly in didFinishLoading, does it log correctly in the singleton, but you can't access it from another class, or is it not logging correctly in the singleton. It would be helpful to see your singleton code. – rdelmar Mar 11 '14 at 03:41
  • If I try to save the variable in my singleton, it does it from within the method. However the minute that I try to use it outside of that in the next view for example, it is as if the value was never saved in my singleton. That is where my problem lies. I never had this problem before and I am baffled as to why it is happening. – Corporate One Mar 11 '14 at 10:17
  • So it looks like you have a property, hostedURL in your singleton. Is that so? Is it declared as a strong property? If you log it from within the singleton, does it log correctly there? – rdelmar Mar 12 '14 at 01:50
  • Yes it logs it fine there. Maybe seeing the whole app would help at this point. Let me know if I can send you the project to view. I have no problems saving to the singleton except from within those delegate methods. – Corporate One Mar 12 '14 at 16:08
  • Sure, I'll take a look at it if you can email it to me at rdelmar@comcast.net. – rdelmar Mar 12 '14 at 20:22

1 Answers1

0

Thanks to the great help from @rdelmar I was able to get through this. Basically in short what was happening was that I was going to the next view before the information was received by my previous view from the web service. So when I was trying to change a label with a value to my Singleton, it was not stored yet. How I got around the issue is that when I click a button I wait until the web services responses and then I add a view to go to the new view. Now my URL that I was waiting reaches me, I save it to Singleton and then I go to the next view.

I will add my code once I can grab it and post it.

Thanks again for all of your help Eric!!! Your patience and help make you a great person on this community.

Regards, Corporate One