I am using a subclass of NSURLProtocol to intercept all HTTP calls and modify the user agent as well as add a other http headers required by my server.
-(id)initWithRequest:(NSURLRequest *)request
cachedResponse:(NSCachedURLResponse *)cachedResponse
client:(id <NSURLProtocolClient>)client
{
NSMutableURLRequest* lInnerRequest;
//************************************************
lInnerRequest = [request mutableCopy];
[lInnerRequest setValue:#"MyUserAgent" forHTTPHeaderField:#"User-Agent"];
//************************************************
self = [super initWithRequest:lInnerRequest
cachedResponse:cachedResponse
client:client];
//************************************************
if (self)
{
self.innerRequest = lInnerRequest;
}
//***********************************00*************
[lInnerRequest release];
//************************************************
return self;
}
My protocol then uses an NSURLConnection
- (void)startLoading
{
self.URLConnection = [NSURLConnection connectionWithRequest:self.innerRequest delegate:self];
}
I then implement all the delegate method in the NSURLConnection by forwarding the call to the equivalent NSURLProtocolClient method.
This works well in general but when I am uploading data to the server, my code which is using NSURLConnection does not get called back on:
connection:didSendBodyData:totalBytesWritten:totalBytesExpectedToWrite:
I understand why this is since I didn't implement that method in the NSURLProtocol as there are no equivalent NSURLProtocolClient method which can be used to report upload progress.
Has someone found any workaround for this?
add this line to your code to make it a HTTP POST request:
[lInnerRequest setHTTPMethod:#"POST"];
Use setProperty:forKey:inRequest: to save NSURLConnection and delegate object, then use propertyForKey:inRequest: to load NSURLConnection object and delegate object in custom NSURLProtocol class, when data sent, use the NSURLConnection object and delegate to call the delegate method
Related
I am trying to solve the following problem:
I am sending a POST request with some additional header values to a specific URL. For that purpose I use NSMutabeURLRequest. It works nice when i NSLog the response, but I also need the URL of the redirect. If I use something like request.URL in the competitionHandler it returns the URL i sent my POST request to, it's not what I need.
Any tips on how to get the URL of the redirect? (It would be nice if it won't change my code significantly.
Below is what I have so far:
url = [NSURL URLWithString:#"https://***"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
//Some additional values are set here
[request setHTTPBody:data];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSLog(#"%#", response);
if (error)
NSLog(#"%s: NSURLConnection error: %#", __FUNCTION__, error);
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"responseString: %#",responseString);
}];
From Apple's Developer Docs:
A redirect occurs when a server responds to a request by indicating that the client should make a new request to a different URL. The NSURLSession, NSURLConnection, and NSURLDownload classes notify their delegates when this occurs.
To handle a redirect, your URL loading class delegate must implement one of the following delegate methods:
For NSURLSession, implement the URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler: delegate method.
For NSURLConnection, implement the connection:willSendRequest:redirectResponse: delegate method.
For NSURLDownload, implement the download:willSendRequest:redirectResponse: delegate method.
In these methods, the delegate can examine the new request and the response that caused the redirect, and can return a new request object through the completion handler for NSURLSession or through the return value for NSURLConnection and NSURLDownload.
The delegate can do any of the following:
Allow the redirect by simply returning the provided request.
Create a new request, pointing to a different URL, and return that request.
Reject the redirect and receive any existing data from the connection by returning nil.
In addition, the delegate can cancel both the redirect and the connection. With NSURLSession, the delegate does this by sending the cancel message to the task object. With the NSURLConnection or NSURLDownload APIs, the delegate does this by sending the cancel message to the NSURLConnection or NSURLDownload object.
The delegate also receives the connection:willSendRequest:redirectResponse: message if the NSURLProtocol subclass that handles the request has changed the NSURLRequest in order to standardize its format, for example, changing a request for http://www.apple.com to http://www.apple.com/. This occurs because the standardized, or canonical, version of the request is used for cache management. In this special case, the response passed to the delegate is nil and the delegate should simply return the provided request.
So basically, you need to make use of the connection:willSendRequest:redirectResponse: delegate method to grab the new url and perform whatever operation you need to on it
The problem is that you're using the sendAsynchronousRequest:queue:completionHandler: method, which uses a completion handler and doesn't take a delegate.
After you implement the delegate method, you'll need to use NSURLConnection's initWithRequest:delegate: or initWithRequest:delegate:startImmediately: method to create the NSURLConnection object instead. You'll also have to implement a delegate method to obtain the data returned by the request.
Alternatively, if you don't have to support anything older than iOS 7 or OS X v10.9, NSURLSession provides the ability to use delegate methods for handling redirection even in combination with methods that take a completion callback.
I have a method which starts an NSURLConnetion to read an IP-Address an return the IP after the connection did finish loading:
- (NSString *)getHansIP
{
self.returnData = [[NSMutableData alloc] init];
NSMutableURLRequest *getIpRequest = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"https://example.com"]];
[getIpRequest setHTTPMethod:#"GET"];
NSURLConnection *ipconn = [NSURLConnection connectionWithRequest:getIpRequest delegate:self];
[ipconn start];
return self.ipString;
}
The problem is that objective-c tries to return the IP-Address (ipString) when the connection did not finished loading yet. I know there is a simple way to fix it but with this way the NSURLConnectionDelegate methods do not getting executed and I need thedidReceiveAuthenticationChallenge Method an the canAuthenticateAgainstProtectionSpace method.
P.S. hope you understand my bad school english :P
You can't return the IP direct from the method, not without blocking the thread anyway, and you can't really do that and handle auth issues.
You need to create an object to manage this which is the delegate for the connection, maintains the connection as an instance variable while it's processing and has a delegate or a completion callback block to pass the IP back with once it's done.
You need to embrace the fact that the connection is asynchronous and not want to return the IP from the method directly.
I've looked around a lot and cant seem to find a proper answer for my problem. As of now I have a network engine and I delegate into that from each of the view controllers to perform my network activity.
For example, to get user details I have a method like this:
- (void) getUserDetailsWithUserId:(NSString*) userId
{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#Details", kServerAddress]]];
request.HTTPMethod = #"POST";
NSString *stringData = [NSString stringWithFormat:#"%#%#", kUserId, userId];
NSData *requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPBody = requestBodyData;
NSURLConnection *conn = [[NSURLConnection alloc] init];
[conn setTag:kGetUserInfoConnection];
(void)[conn initWithRequest:request delegate:self];
}
And when I get the data in connectionDidFinishLoading, I receive the data in a NSDictionary and based on the tag I've set for the connection, I transfer the data to the required NSDictionary.
This is working fine. But now I require two requests going from the same view controller. So when I do this, the data is getting mixed up. Say I have a connection for search being implemented, the data from the user details may come in when I do a search. The data is not being assigned to the right NSDictionary based on the switch I'm doing inside connectionDidFinishLoading. I'm using a single delegate for the entire network engine.
I'm new to NSURLConnection, should I setup a queue or something? Please help.
EDIT
Here's the part where I receive data in the connectionDidFinishLoading:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
if ([connection.tag integerValue] == kGetUserDetails)
networkDataSource.userData = self.jsonDetails;
if ([connection.tag integerValue] == kSearchConnection)
networkDataSource.searchData = self.jsonDetails;
}
and after this I have a switch case that calls the required delegate for the required view controller.
Anil here you need to identify for which request you got the data,
simplest way to check it is as below,
- (void)connectionDidFinishLoading:(NSURLConnection *)conn
{
// Check URL value for request, url for search and user details will be different, put if condition as per your need.
conn.currentRequest.URL
}
Try using conn.originalRequest.URL it will give original request.
You can do in many ways to accomplish your task as mentioned by others and it will solve your problem . But if you have many more connections , you need to change your approach.
You can cretae a subclass of NSOperation class. Provide all the required data, like url or any other any informmation you want to get back when task get accomplish , by passing a dictionary or data model to that class.
In Nsoperation class ovewrite 'main' method and start connection in that method ie put your all NSURRequest statements in that method. send a call back when download finish along with that info dict.
Points to be keep in mind: Create separte instance of thet operation class for evey download, and call its 'start method'.
It will look something like :
[self setDownloadOperationObj:[[DownloadFileOperation alloc] initWithData:metadataDict]];
[_downloadOperationObj setDelegate:self];
[_downloadOperationObj setSelectorForUpdateComplete:#selector(callBackForDownloadComplete)];
[_downloadOperationObj setQueuePriority:NSOperationQueuePriorityVeryHigh];
[_downloadOperationObj start];
metaDict will contain your user info.
In DownloadFileOperation class you will overwrite 'main' method like :
- (void)main {
// a lengthy operation
#autoreleasepool
{
if(self.isCancelled)
return;
// //You url connection code
}
}
You can add that operation to a NSOperationQueue if you want. You just need to add the operation to NSOperationQueue and it will call its start method.
Declare two NSURLConnection variables in the .h file.
NSURLConnection *conn1;
NSURLConnection *conn2;
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
if(connection == conn1){
}
else if(connection == conn2){
}
}
hi I have an UITableView. It loads numberof data from a web service. What I want to load this tableview 10 by 10.Initially it loads first 10 items. When user scroll to the end of the UITableView it should load next 10 of records from the server. so in my scrollviewDidEndDeclarating delegate I put like this
`
if (scrollView.tag==24) {
[self performSelector:#selector(loadingalbumsongs:) withObject:nil afterDelay:0.1];
}`
but the problem is when I stop the scroll it is getting stuck untill load the table view. Can anybody give me a solution for this
Thanks
Try NSURLCONNECTION that will help you to call asynchronous webservice
A NSURLConnection object is used to perform the execution of a web service using HTTP.
When using NSURLConnection, requests are made in asynchronous form. This mean that you don't wait the end of the request to continue,
This delegate must have to implement the following methods :
connection:didReceiveResponse : called after the connection is made successfully and before receiving any data. Can be called more than one time in case of redirection.
connection:didReceiveData : called for each bloc of data.
connectionDidFinishLoading : called only one time upon the completion of the request, if no error.
connection:didFailWithError : called on error.
EXAMPLE: -
NSData *data = [[NSMutableData alloc] init];
NSURL *url_string = [NSURL URLWithString:
#"Your URL"];
NSURLRequest *request = [NSURLRequest requestWithURL:url_string];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request
delegate:self];
if (!conn) {
// this is better if you #throw an exception here
NSLog(#"error while starting the connection");
[data release];
}
for each block of raw data received you can append your data here in this method :
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)someData {
[data appendData:someData];
}
connectionDidFinishLoading will call at the end of successfully data receivied
use this code for load more action
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
//scrollView.contentSize.height-scrollView.frame.size.height indicates UItableView scrool end
if (scrollView.contentOffset.y >= scrollView.contentSize.height-scrollView.frame.size.height)
{
if(loadMore)
{
loadmore=no;
//call your Web service
}
}
}
I need to check and evaluate the HTTP Status Codes in my iPhone app. I've got an NSURLRequest object and an NSURLConnection that successfully (I think) connect to the site:
// create the request
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.apple.com/"]
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 that will hold
// the received data
// receivedData is declared as a method instance elsewhere
receivedData=[[NSMutableData data] retain];
} else {
// inform the user that the download could not be made
}
I got this code here: https://web.archive.org/web/20100908130503/http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html
But it doesn't (as far as I can see) say anything about accessing HTTP Status codes.
How to make a connection to a site and then check the HTTP Status Codes of that connection?
This is how I do it:
#pragma mark -
#pragma mark NSURLConnection Delegate Methods
- (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response {
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
int responseStatusCode = [httpResponse statusCode];
}
But I'm using an asynchronous NSURLConnection, so this may not help you. But I hope it does anyway!