How to return data received from a web service in the lens (iPhone)?

This may be a dumb question. Sorry if so.

But I'm working on a project that uses web services. I can connect to the web service and get the data I need.

I would like to have a method that returns this data received from the web service to the caller. The only problem is that the data is received only in the ConnectionDidFinishLoading method, and I cannot access this data from my method.

here is my code that works great:

- (NSData *) dataForMethod:(NSString *)webMethod withPostString:(NSString *)postString
{
    NSURL *url = [NSURL URLWithString:[SigameWebServiceAddress stringByAppendingFormat:@"%@%@", @"/", webMethod]];
    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
    NSString *msgLength = [NSString stringWithFormat:@"%d", [postString length]];

    [req addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [req addValue:msgLength forHTTPHeaderField:@"Content-Length"];
    [req setHTTPMethod:@"POST"];
    [req setHTTPBody: [postString dataUsingEncoding:NSUTF8StringEncoding]];

    conn = [[NSURLConnection alloc] initWithRequest:req delegate:self];
    if (conn) 
    {
        webData = [NSMutableData data];
    }   

    // I WOULD LIKE TO RETURN WEBDATA TO THE CALLER HERE, BUT WEBDATA IS EMPTY NOW, THE  
    //connectionDidFinishLoading ONLY GETS CALLED WITH THE DATA I WANT AFTER THE COMPILER
    //IS DONE EXECUTING MY METHOD.
}

-(void) connection:(NSURLConnection *) connection didReceiveResponse:(NSURLResponse *) response 
{
    [webData setLength: 0];
}

-(void) connection:(NSURLConnection *) connection didReceiveData:(NSData *) data 
{
    [webData appendData:data];
}

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

-(void) connectionDidFinishLoading:(NSURLConnection *) connection 
{
    NSLog(@"DONE. Received Bytes: %d", [webData length]);

    NSString *theXML = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];

    //---shows the XML---
    NSLog(@"%@", theXML);  //NOW, THIS IS THE DATA I WANT. BUT HOW CAN I RETURN THIS TO 
                           //THE CALLER. I MEAN, THE CALLER THAT CALLED MY METHOD 
                           //+ (NSData *) dataForMethod: withPostString:
}

Any help here is appreciated! Thanks

+5
source share
5 answers

There are two ways around this.

  • Create Delegate Interface
  • Use blocks

- (.. ). , , , .

, :

1.

, , , . , :

:

@protocol RequestClassDelegate <NSObject>

- (void)requestCompleted:(ResponseClass *)data;
- (void)requestError:(NSError *)error;

@end

, , :

@interface RequestClass : NSObject

- (void)makeRequest:(id<RequestClassDelegate>)delegate;

@end

, :

@implementation RequestClass
{
    __weak id<RequestClassDelegate> _delegate;
}

// Connection Logic, etc.

- (void)makeRequest:(id<RequestClassDelegate>)delegate
{
    _delegate = delegate;
    // Initiate the request...
}

-(void) connectionDidFinishLoading:(NSURLConnection *) connection 
{
    NSString *theXML = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];

    // Processing, etc.

    // Here we'll call the delegate with the result:
    [_delegate requestCompleted:theResult];
}

@end

2.

, , , . RequestClass :

typedef void (^requestCompletedBlock)(id);
typedef void (^requestErrorBlock)(NSError *);
@interface RequestClass : NSObject

@property (nonatomic, copy) requestCompletedBlock completed;
@property (nonatomic, copy) requestErrorBlock errored;

- (void)makeRequest:(requestCompletedBlock)completed error:(requestErrorBlock)error;

@end

:

@implementation RequestClass

@synthesize completed = _completed;
@synthesize errored = _errored;

// Connection Logic, etc.

- (void)makeRequest:(requestCompletedBlock)completed error:(requestErrorBlock)error
{
    self.completed = completed;
    self.errored = error;
    // Initiate the request...
}

-(void) connectionDidFinishLoading:(NSURLConnection *) connection 
{
    NSString *theXML = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];

    // Processing, etc.

    // Here we'll call the delegate with the result:
    self.completed(theResult);
}

@end
+11

, , , ( NSURLConnection ), . , , . , @Steve , .

, . :

conn = [[NSURLConnection alloc] initWithRequest:req delegate:self];
[conn start]; // I presume you have this somewhere
if (conn) 
{
    webData = [NSMutableData data];
} 

- :

 NSURLResponse *response = nil;
 NSError *error = nil;
 webdata = [NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&error];
 if (webdata) {
     return webdata;
 }
 else {
     // Handle error by looking at response and/or error values
     return nil;
 }

, - . , . , - - , URL, .

+2

, . , Objective-C, , . .

The Post : http://kerkermeister.net/how-to-build-an-cocos2d-ios-app-communicating-with-a-restful-api-the-sequence/

, , . : - , , Web API - , HTTP- -API - HttpRequest, NSURLC IOS - ,

+2

, , connectionDidFinishLoading, . , , , , , , .

, , :

NSURLConnections ? Ios

0

XML, . XML- Objective C XML. , , ....

http://nfarina.com/post/2843708636/a-lightweight-xml-parser-for-ios

It is a very lightweight parser for extracting values ​​from XML. I used many times with great success and a bit of trouble. This is how I request a web address and turn it into data.

 NSString *query = [NSString stringWithFormat:@"http://WEB_ADDRESS_FOR_XML];
    NSURL *URL = [NSURL URLWithString:query];
    NSData *data = [NSData dataWithContentsOfURL:URL];

Or using NSURLConnection, in the received data:

-(void) connection:(NSURLConnection *) connection didReceiveData:(NSData *) data 
{
    //USE THE DATA RETURNED HERE....
}

Then use Parser from my link to get the content:

 SMXMLDocument *document = [SMXMLDocument documentWithData:data error:NULL];

    NSLog("\nXML Returned:%@",document);
-1
source

All Articles