how to get response body in IOS? - ios

Now I want to get the response body. I'm a new guy in IOS developer. I only kown I can use response.statusCode to get httpstatuscode ,such like 400,500 and so on. But how to get response body. Maybe allheaderFileds or data or error.Description?

The full details are available at: URL Loading System Programming Guide
You'll need a object that is the delegate of the NSURLConnection. You'll need to have a receivedData member variable and you'll need to implement the delegate methods:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[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];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// do something with the data
// release the connection, and the data object
[connection release];
[receivedData release];
}

Related

Asynchronous web-service call returns with datatable in IOS

I have created a connection using NSURLConnection (Asynchronous web-service call).
i have added all delegates like
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[m_webData setLength: 0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[m_webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"ERROR with theConenction");
[connection release];
[m_webData release];
}
i am receiving data ... but i am sending Datable, i do not know how to parse data, how to read data.
my web-service get hit and sends data but how do parse receive datable.
First , as you have received your entire data in m_webData (assuming it is an instance of NSObject) , use this to parse xml using NSXML parser or TBXML parser. Now, real point is that you have to learn how to parse using either of two or any other i don't know (depending on your data received- JSON or XML).
You can learn :
parsing from Xml parsing in iOS tutorial
also TBXML from :http://www.tbxml.co.uk/TBXML/Guides_-_Loading_an_XML_document.html
or http://www.raywenderlich.com/553/xml-tutorial-for-ios-how-to-choose-the-best-xml-parser-for-your-iphone-project
It is better for you to learn first and then use it instead of asking for code.

defunct NSURLConnection never executes or times out

I'm running a LOT of asynchronous (delegate, not block) NSURLConnections simultaneously, and they all come back very quickly as I'm hitting a LAN server.
Every so often, one NSURLConnection will go defunct and never return.
connection:willSendRequest: is called but connection:didReceiveResponse: (and failure) is not.
Any ideas? I'm wondering if I should make a simple drop-in replacement using CFNetwork instead.
Edit: There's really not much code to show. What I've done is created a wrapper class to download files. I will note that the problem happens less when I run the connection on a separate queue - but still happens.
The general gist of what I'm doing is creating a download request for each cell as a tableview scrolls (in cellForRowAtIndexPath) and then asynchronously loading in an image file to the table cell if the cell is still visible.
_request = [NSMutableURLRequest requestWithURL:_URL];
_request.cachePolicy = NSURLRequestReloadIgnoringCacheData;
_request.timeoutInterval = _timeoutInterval;
if(_lastModifiedDate) {
[_request setValue:[_lastModifiedDate RFC1123String] forHTTPHeaderField:#"If-Modified-Since"];
}
_connection = [[NSURLConnection alloc] initWithRequest:_request
delegate:self
startImmediately:NO];
[_connection start];
As requested, instance variables:
NSMutableURLRequest *_request;
NSURLConnection *_connection;
And delegate methods:
- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response {
NSLog(#"%# send", _URL);
return request;
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(#"%# response", _URL);
_response = (id)response;
// create output stream
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
_receivedLength += data.length;
_estimatedProgress = (Float32)_receivedLength / (Float32)_response.expectedContentLength;
[_outputStream write:data.bytes maxLength:data.length];
// notify delegate
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// close output stream
// notify delegate
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"%# failure", _URL);
// notify delegate
}
- (void)connection:(NSURLConnection *)connection
didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
if(_credential && challenge.previousFailureCount == 0) {
[[challenge sender] useCredential:_credential forAuthenticationChallenge:challenge];
}
}
After poking around in profiler, I found a lead, and it gave me a hunch.
My credentials were failing (not sure why...) and so previousFailureCount was not 0, and hence I wasn't using my credential object.
Changed the code to this and I have no problems:
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
if(_credential) {
[[challenge sender] useCredential:_credential forAuthenticationChallenge:challenge];
}
}
A NSURLConnection will send either didReceiveResponse or didFailWithError.
Often, you're dealing with timeouts before didFailWithError occurs.

Singleton for different NSURLConnection [duplicate]

This question already has an answer here:
How to identify WHICH NSURLConnection did finish loading when there are multiple ones?
(1 answer)
Closed 9 years ago.
I always used for connect with Server singleton class. I didn't check response from server and easy take data. Now I need use 10 different requests. I create property NSURLConnection. So how can I identify what connections I use in delegate methods like
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
Because from each request I take different data
What you could do is have a custom connection class representing a connection, its data, and optionally some info about the connection. I use this:
#interface MyConnection : NSObject
#property NSURLConnection *connection;
#property id info;
#property NSMutableData *data;
#end
Then just put the connections in an array, and compare the actual NSURLConnection objects to each other, in order to find out which connection received data/failed etc.
Creating a connection:
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:someRequest delegate:self];
if (connection){
MyConnection *con = [[MyConnection alloc] init];
con.connection = connection;
con.data = [NSMutableData data];
[self.arrayWithConnections addObject:con];
}
The methods:
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
MyConnection *con = [self getConnection:connection]
[con.data appendData:data];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
MyConnection *con = [self getConnection:connection];
[con.data setLength:0];
}
-(MyConnection *)getConnection:(NSURLConnection *)con
{
for (MyConnection *myCon in self.arrayWithConnections)
if ([con isEqual: myCon.connection])
return myCon;
return nil;
}

How i can get total Download figures for Wifi and GPRS (GSM) separately for iPhone / iPad

How to get total downloaded bytes figures and how i can come to know that how many bytes are downloaded using wifi and how many using GSM (iPhone + iPad)?
Thanks in advance.
Muzammal Hussain.
You will need to use the following delegate method of NSURLConnection :
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// Append the new data to receivedData.
// receivedData is an instance variable declared elsewhere.
[receivedData appendData:data];
}
In this way you get the NSData in one variable. Then you can get its size in the delegate method:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
OR
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
With help of the line:
NSLog(#"Data downloaded==%d",receivedData.length);
Hope this helps.

How to check downloading data percentage from internet in iOS?

I am trying to download data from internet to NSData in iOS.
When I download data from internet , I can't see how many percentage downloaded from server.
I'm not using UIWebView.
download sound (.mp3) from Internet with NSData.
Is there anyways can I know how much data downloaded from internet?
Thanks in advance.
Steps:
1) Create a NSURLConnection with a request to the .mp3's URL.
2) Set self as the delegate of this connection.
3) Implement the NSURLConnectionDataDelegate protocol. ( Add next to your class's interface declaration.
4) Implement these methods:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
statusCode = [httpResponse statusCode];
if ((statusCode/100) == 2)
{
contentLength = [httpResponse expectedContentLength];
if (contentLength == NSURLResponseUnknownLength)
NSLog(#"unknown content length %ld", contentLength);
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
bytesSum += [data length];
percent = (float)bytesSum / (float)contentLength;
// append the new data to the receivedData
[receivedData appendData:data]; //received data is a NSMutableData ivar.
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
//the end. Write your data ( stored in receivedData ) to a local .mp3 file.
}
Hope this helps.
Cheers!
I would suggest to have a look at this: ASIHTTPRequest
You could easily track upload and download process with it and other nice stuff.
Sebastian

Resources