Cannot call method in objective c - objective-c

I'm having difficulty understanding how to call a method. Here's the code:
- (void)beachJSON
{
// Build the string to call Beach API
NSString *urlString = [NSString stringWithFormat:#"http://nrw-bwq-dev-api.azurewebsites.net/api/Pull"];
// Create NSURL string from formatted string
NSURL *url = [NSURL URLWithString:urlString];
// Setup and start async download
NSURLRequest *request = [[NSURLRequest alloc] initWithURL: url];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection release];
[request release];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// Store incoming data into a string
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
results = [jsonString JSONValue];
}
- (NSArray *)getBeachList {
[self beachJSON];
return results;
}
I call getBeachList from another class to populate 'results', beachJSON is called fine but I need to call
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
Within
- (NSArray *)getBeachList
i.e. right here
- (NSArray *)getBeachList {
[self beachJSON];
//This is where I want to call it to populate results before it is returned
return results;
}
Calling getBeachList will call beachJSON but the connection method will be skipped over leaving 'results' nil
If i try simply putting
[self connection:(NSURLConnection *)connection didReceiveData:(NSData *)data]
I get a expected expression error on that line.
I'm pretty new to objective c so any help would be great.

You don't need to call this method.
It's a delegate method of NSURLConnection.
What you need is to set a delegate for connection and method will be called by connection when it downloads any data.

You should not call connection:didReceiveData: by yourself. This is an event which is only supposed to be fired by the NSURLConnection instance. As far as I can see the only thing you are missing is the start call, which actually makes the NSURLConnection perform the request.
Try this:
NSURLRequest *request = [[NSURLRequest alloc] initWithURL: url];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
Then you should see that your NSURLConnection instance will call your implementation of connection:didReceiveData:.
If you want to be sure that your data is fully loaded you should be using this event instead:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
The connection:didReceiveData: will be called multiple times if your data size is large enough. Every time the NSURLConnection receives data it will invoke connection:didReceiveData:. connectionDidFinishLoading: will only be called once when all your data is ready.

Related

unable to load data from webservice into id type of variable

I am trying to load data from server into id result variable, my url is working perfectly i can see data on the browser, but the data loading process is very slow(15 secs ) and the result getting Output data id result is nil
Class: MyWebservices :-
-(id)getResponseFromServer:(NSString*)requestString
{
id result;
NSError *error;
NSURLResponse *response = nil;
NSURL *url = [NSURL URLWithString:[requestString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
NSData * resultData= [[NSData alloc]init];
resultData = [NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&error];
Class: WebserviceCallingClass
- (void)viewDidLoad
{
id result = [AppDelegate.MyWebservices getResponseFromServer:urlString] ;
}
Use asynchronous request.
1) Use NSURLConnectionDelegate and declares
in your interface class a:
NSMutableData *_responseData;
2)Send your asynchronous request and set in timeout interval a time major than 15 seconds
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://uri"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20];
conn = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
[conn scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
[conn start];
3) Implement your delegate methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
// A response has been received, this is where we initialize the instance var you created
// so that we can append data to it in the didReceiveData method
// Furthermore, this method is called each time there is a redirect so reinitializing it
// also serves to clear it
_responseData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
// Append the new data to the instance variable you declared
[_responseData appendData:data];
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
willCacheResponse:(NSCachedURLResponse*)cachedResponse {
// Return nil to indicate not necessary to store a cached response for this connection
//NSLog(#"cache");
return nil;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// The request is complete and data has been received
// You can parse the stuff in your instance variable now
}
}
or in synchronous request try to edit your NSMutableURLRequest
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60.f];

NSUrlRequest Not Working Objective C

I am trying to use the code below to 'trigger' the web address. The web server doesn't return any data. But the NSURLConnection is being established.
NSString *serverAddressTest = #"http://domain.com";
NSString *fullWebAddress = [NSString stringWithFormat:#"%#?CustomerName=%#&ContactNo=%#&Products=%#",serverAddressTest,customer,contactnumber,allProductsInString];
NSURL *url = [NSURL URLWithString:fullWebAddress];
NSURLRequest *theRequest=[NSURLRequest requestWithURL:url];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
NSMutableData *webData = [NSMutableData data];
NSLog(#"%#",webData);
}
else {
NSMutableData *webData = [NSMutableData data];
NSLog(#"%#",webData);
}
When you write:
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest
delegate:self];
you are starting an asynchronous url connection.
Then immediately after that you are testing whether the connection was successful or not and creating an instance of NSMutableData with local scope. Your NSURLConnectionDelegate methods (which you haven't posted) will not have access to this locally-scoped NSMutableData variable.
Have you indeed implemented the methods of the NSURLConnectionDelegate protocol?
Try to send synchronous request to localise the problem:
NSError *error;
NSData *returnData = [NSURLConnection sendSynchronousRequest: theRequest
returningResponse: nil
error: &error];
NSLog(#"error = %#, \ndata = %#", error, returnData);
You also need to also implement the delegate Protocols. ( As NSBum says)
Using Apples example
shown here is the data is returned when the parts are put together.:
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.apple.com/"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
// Create the NSMutableData to hold the received data.
// receivedData is an instance variable declared elsewhere.
receivedData = [NSMutableData dataWithCapacity: 0];
// create the connection with the request
// and start loading the data
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (!theConnection) {
// Release the receivedData object.
receivedData = nil;
NSLog(#"FAIL " );
// Inform the user that the connection failed.
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(#" response %#", response);
// This method is called when the server has determined that it
// has enough information to create the NSURLResponse object.
// It can be called multiple times, for example in the case of a
// redirect, so each time we reset the data.
// receivedData is an instance variable declared elsewhere.
[receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// Append the new data to receivedData.
// receivedData is an instance variable declared elsewhere.
[receivedData appendData:data];
NSLog(#" receivedData %#", receivedData);
}
receivedData is not local but declared elsewhere. (NSMutableData* receivedData;)
I do not use this much so cannot expand further without reading the docs fully myself; which is what you need to do. :-)

Downloading images and captions with JSON in xcode

I have googled this numerous times, with lots of different phrasing, but nothing seems to have exactly what I am after.
What I want to do is to download images and captions into a NSArray with JSON. I do not want to save these images, only display them in a UICollectionView. It would be much easier to be able to download multiple images using the same URL, not just 1 image per URL.
Since I am a fairly newbie programmer, I only know how to use NSURLRequest. This is some of my code:
NSString *getDataURL = [[NSString stringWithFormat:#"URL and a couple of perams", var, var2] stringByReplacingOccurencesOfString:#" " withString:#"%20"];
NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:getDataURL]];
[[NSURLConnection alloc] initWithRequest:req delegate:self];
And then a bit later on in the connectionDidFinishLoading: method:
NSArray *dataArray = [NSJSONSerialization JSONObjectWithData:data options:nil error:nil]; // variable 'data' is an NSMutableData declared in .h
Please advise on what to do, or even if it's possible!
Thanks in advance!
You can do it this way:
-(void) loadImageAtURL:(NSString*)url {
NSURL *requestURL = [[NSURL alloc] initWithString:url];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:requestURL cachePolicy:nil timeoutInterval:45.0];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
imageData = [[[NSMutableData alloc] init] retain];
}
And handle response in NSURL delegate methods like:
- (void)connection:(NSURLConnection *)connection
didReceiveData:(NSData *)data {
[imageData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)aConnection {
// RELEASE THE CONNECTION
[connection release];
// CREATE NEW UIIMAGE FROM THE DATA
UIImage *image = [[[UIImage alloc] initWithData:imageData] retain];
[imageData release];
[yourImageView setImage:image];
[image release];
}
- (void)connection:(NSURLConnection *)connection
didFailWithError:(NSError *)error {
// Handle error
}
Hope these methods will give you direction how to carry out things. You make the JSON handling as per your API response in didReceiveData:(NSData *)data and use that data later in connectionDidFinishLoading:
I'm not sure I understand exactly what you are trying to ask but if your goal is to get a list of images/captions using JSON give AFNetworking a try
https://github.com/AFNetworking/AFNetworking

how to fetch page content of an URL Request (post)

I have a little Mac application which should be able to post Data to my web server which saves the data in a database. Now that's the Code I have now:
NSData *postData = [urlString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://..."]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection * connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection) NSLog(#"Done");
And it works fine. But now I want to check whether the data was correct (and stored in the database) or something (like eMail) is wrong. The PHP file prints e.g. "email incorrect" out if the E-Mail is not correct.
But how can I fetch this data (which PHP prints out) in Xcode that the App knows whether it was successful or not?
Thanks for answers!
You need to implement the NSURLConnectionDelegate methods connection:didReceiveData: and connectionDidFinishLoading:
According to the docs didReceiveData: may be called multiple times per NSURLRequest (i.e. the response will not always arrive all at once) so the recommended method is to append the incoming data to buffer during connection:didReceiveData: and then do any processing on the data in connectionDidFinishLoading:.
You could create a property on your class like this:
#property (nonatomic, strong) NSMutableData *dataBuffer;
And instantiate your buffer during viewDidLoad:
- (void)viewDidLoad
{
[super viewDidLoad];
self.dataBuffer = [[NSMutableData alloc] init];
// do any other setup your class requires...
}
And then implement the delegate methods:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
// clear the buffer in case it has been used previously
[self.dataBuffer setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.dataBuffer appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection*)connection
{
NSString *response = [NSString stringWithUTF8String:[self.dataBuffer bytes]]);
NSLog(#"response from HTTP request=>%#", response);
}
This can all also be done using a third-party networking library like ASIHTTPRequest (which is no longer under active develoment) or AFNetworking, but sometimes those can be overkill depending upon what you are trying to accomplish
Implement the delegate method for the NSURLConnection,
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response.
This method is called by the app when the request finishes. You can access response data using the 'response' parameter.
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;
Then just convert the 'data' parameter into a string using:
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
Then you can search the response for whatever string you want, e.g., "email incorrect".
PS: I generally don't use NSURLConnection/NSURLRequest for HTTP requests, I'd recommend you check out ASIHTTPRequest for really simple HTTP requests/connections.
Hope this helps.

Retrieving data from website to iphone

I was recently looking at an example from apple about NSURLConnection and I tried implementing it into my code but I am not sure if am I doing it right.
Basically I want the connection to go to my website where I have it connected to a php script that runs the search within my database and then echo's it to the browser. I want the iphone to take the line that is echoed and hold it into a string variable. This is my code.
Is this correctly done?
Thank you in advance
NSString *stringToBeSent= [[NSString alloc] initWithFormat:
#"http:/xxxxx/siteSql.php? data=%#",theData];
NSURLRequest *theRequest=[NSURLRequest requestWithURL:
[NSURL URLWithString:stringToBeSent]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
// create the connection with the request
// and start loading the data
NSURLConnection *theConnection=[[NSURLConnection alloc]
initWithRequest:theRequest delegate:self];
if (theConnection) {
// Create the NSMutableData to hold the received data.
// receivedData is an instance variable declared elsewhere... in my .h file
// NSMutableData *receivedData;
receivedData = [[NSMutableData data] retain];
//convert NSMutableData to a string
NSString *stringData= [[NSString alloc]
initWithData:receivedData encoding:NSUTF8StringEncoding];
NSLog (#"result%#", receivedData);
} else {
// Inform the user that the connection failed.
NSLog(#"failed");
}
I think you might be missing a couple things:
In the method that you use to trigger retrieving the data make sure you release the old data before initializing:
[retrievedData release];
retrievedData=[[NSMutableData alloc] init];
I assume that space is a typo or something for the URL?
You don't need to call requestWithURL:cachePolicy:timeoutInterval: requestWithURL: uses the same defaults as you chose.
The data will come in blocks. You've got to handle that over time, outside this method, using the delegate method connection:didReceiveData:, like so:
- (void)connection:(NSURLConnection *)conn didReceiveData:(NSData *)data
{
[receivedData appendData:data];
}
Similarly, if you want something done with the data once it's all received, you do it in connectionDidFinishLoading: NOTE THAT THE CONNECTION IS RELEASED so it has to be defined in your header as an instance variable (eg. NSURLConnection *connection;
- (void)connectionDidFinishLoading:(NSURLConnection *)conn
{
NSString *stringData= [[NSString alloc]
initWithData:receivedData encoding:NSUTF8StringEncoding];
NSLog(#"Got data? %#", stringData);
[connection release];
connection = nil;
// Do unbelievably cool stuff here //
}
Also look into the other delegate methods like connection:didFailWithError: You probably want to release the connection and stringData there as well, in case of an error.
I hope that's of some help! Enjoy!