My apps open iTunes Affliate links directly using the standard sharedApplication.OpenURL. However, Apple recommends the following code.
Is there a C# version to support Xamarin?
// Process a LinkShare/TradeDoubler/DGM URL to something iPhone can handle
(void)openReferralURL:(NSURL *)referralURL
{
NSURLRequest *theRequest=[NSURLRequest requestWithURL:referralURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
[conn release];
}
// Save the most recent URL in case multiple redirects occur
// "iTunesURL" is an NSURL property in your class declaration
(NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response
{
if (response) {
NSMutableURLRequest *r = [[request mutableCopy] autorelease]; // original request
[r setURL: [request URL]];
self.iTunesURL = [r URL];
if ([self.iTunesURL.host hasSuffix:#"itunes.apple.com"]) {
[[UIApplication sharedApplication] openURL:self.iTunesURL];
}
return r;
} else {
return request;
}
}
Couldn't find an existing API, so I wrote it:
Enjoy!
NSUrlRequest theRequest;
NSUrlConnection conn;
void Process (NSUrl url)
{
theRequest = new NSUrlRequest (url, NSUrlRequestCachePolicy.UseProtocolCachePolicy, 30);
var del = new LinkDelegate ();
conn = new NSUrlConnection (theRequest, del);
conn.Start ();
}
}
class LinkDelegate: NSUrlConnectionDelegate
{
public override NSUrlRequest WillSendRequest (NSUrlConnection connection, NSUrlRequest request, NSUrlResponse response)
{
if (response!=null) {
var url = request.Url;
if (url.Host.ToLower ().Contains ("itunes.apple.com"))
UIApplication.SharedApplication.OpenUrl (url);
return NSUrlRequest.FromUrl (url);
} else {
return request;
}
}
}
Related
I'm trying to send an HTTP Post with the iOS application that I'm developing but the push never reaches the server although I do get a code 200 as response (from the urlconnection). I never get a response from the server nor does the server detect my posts (the server does detect posts coming from android)
I do use ARC but have set pd and urlConnection as strong.
This is my code for sending the request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]
initWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#%#",dk.baseURL,#"daantest"]]];
[request setHTTPMethod:#"POST"];
[request setValue:#"text/xml"
forHTTPHeaderField:#"Content-type"];
NSString *sendString = #"<data><item>Item 1</item><item>Item 2</item></data>";
[request setValue:[NSString stringWithFormat:#"%d", [sendString length]] forHTTPHeaderField:#"Content-length"];
[request setHTTPBody:[sendString dataUsingEncoding:NSUTF8StringEncoding]];
PushDelegate *pushd = [[PushDelegate alloc] init];
pd = pushd;
urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:pd];
[urlConnection start];
this is my code for the delegate
#import "PushDelegate.h"
#implementation PushDelegate
#synthesize data;
-(id) init
{
if(self = [super init])
{
data = [[NSMutableData alloc]init];
[data setLength:0];
}
return self;
}
- (void)connection:(NSURLConnection *)connection didWriteData:(long long)bytesWritten totalBytesWritten:(long long)totalBytesWritten
{
NSLog(#"didwriteData push");
}
- (void)connectionDidResumeDownloading:(NSURLConnection *)connection totalBytesWritten:(long long)totalBytesWritten expectedTotalBytes:(long long)expectedTotalBytes
{
NSLog(#"connectionDidResumeDownloading push");
}
- (void)connectionDidFinishDownloading:(NSURLConnection *)connection destinationURL:(NSURL *)destinationURL
{
NSLog(#"didfinish push #push %#",data);
}
- (void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite
{
NSLog(#"did send body");
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[self.data setLength:0];
NSHTTPURLResponse *resp= (NSHTTPURLResponse *) response;
NSLog(#"got response with status #push %d",[resp statusCode]);
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)d
{
[self.data appendData:d];
NSLog(#"recieved data #push %#", data);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *responseText = [[NSString alloc] initWithData:self.data encoding:NSUTF8StringEncoding];
NSLog(#"didfinishLoading%#",responseText);
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[[[UIAlertView alloc] initWithTitle:NSLocalizedString(#"Error ", #"")
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:NSLocalizedString(#"OK", #"")
otherButtonTitles:nil] show];
NSLog(#"failed &push");
}
// Handle basic authentication challenge if needed
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
NSLog(#"credentials requested");
NSString *username = #"username";
NSString *password = #"password";
NSURLCredential *credential = [NSURLCredential credentialWithUser:username
password:password
persistence:NSURLCredentialPersistenceForSession];
[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
}
#end
The console always prints the following lines and the following lines only:
2013-04-01 20:35:04.341 ApprenticeXM[3423:907] did send body
2013-04-01 20:35:04.481 ApprenticeXM[3423:907] got response with status #push 200
2013-04-01 20:35:04.484 ApprenticeXM[3423:907] didfinish push #push <>
The following code describes a simple example using POST method.(How one can pass data by POST method)
Here, I describe how one can use of POST method.
1. Set post string with actual username and password.
NSString *post = [NSString stringWithFormat:#"Username=%#&Password=%#",#"username",#"password"];
2. Encode the post string using NSASCIIStringEncoding and also the post string you need to send in NSData format.
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
You need to send the actual length of your data. Calculate the length of the post string.
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
3. Create a Urlrequest with all the properties like HTTP method, http header field with length of the post string. Create URLRequest object and initialize it.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
Set the Url for which your going to send the data to that request.
[request setURL:[NSURL URLWithString:#"http://www.abcde.com/xyz/login.aspx"]];
Now, set HTTP method (POST or GET). Write this lines as it is in your code.
[request setHTTPMethod:#"POST"];
Set HTTP header field with length of the post data.
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
Also set the Encoded value for HTTP header Field.
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
Set the HTTPBody of the urlrequest with postData.
[request setHTTPBody:postData];
4. Now, create URLConnection object. Initialize it with the URLRequest.
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
It returns the initialized url connection and begins to load the data for the url request. You can check that whether you URL connection is done properly or not using just if/else statement as below.
if(conn) {
NSLog(#"Connection Successful");
} else {
NSLog(#"Connection could not be made");
}
5. To receive the data from the HTTP request , you can use the delegate methods provided by the URLConnection Class Reference.
Delegate methods are as below.
// This method is used to receive the data which we get using post method.
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data
// This method receives the error report in case of connection is not made to server.
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
// This method is used to process the data after connection has made successfully.
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
Also Refer This and This documentation for POST method.
And here is best example with source code of HTTPPost Method.
-(void)sendingAnHTTPPOSTRequestOniOSWithUserEmailId: (NSString *)emailId withPassword: (NSString *)password{
//Init the NSURLSession with a configuration
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];
//Create an URLRequest
NSURL *url = [NSURL URLWithString:#"http://www.example.com/apis/login_api"];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
//Create POST Params and add it to HTTPBody
NSString *params = [NSString stringWithFormat:#"email=%#&password=%#",emailId,password];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
//Create task
NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
//Handle your response here
NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSLog(#"%#",responseDict);
}];
[dataTask resume];
}
I am not really sure why, but as soon as I comment out the following method it works:
connectionDidFinishDownloading:destinationURL:
Furthermore, I don't think you need the methods from the NSUrlConnectionDownloadDelegate protocol, only those from NSURLConnectionDataDelegate, unless you want some download information.
Heres the method I used in my logging library: https://github.com/goktugyil/QorumLogs
This method fills html forms inside Google Forms. Hope it helps someone using Swift.
var url = NSURL(string: urlstring)
var request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.HTTPBody = postData.dataUsingEncoding(NSUTF8StringEncoding)
var connection = NSURLConnection(request: request, delegate: nil, startImmediately: true)
Sending an HTTP POST request on iOS (Objective c):
-(NSString *)postexample{
// SEND POST
NSString *url = [NSString stringWithFormat:#"URL"];
NSString *post = [NSString stringWithFormat:#"param=value"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:#"POST"];
[request setURL:[NSURL URLWithString:url]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error = nil;
NSHTTPURLResponse *responseCode = nil;
//RESPONDE DATA
NSData *oResponseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&responseCode error:&error];
if([responseCode statusCode] != 200){
NSLog(#"Error getting %#, HTTP status code %li", url, (long)[responseCode statusCode]);
return nil;
}
//SEE RESPONSE DATA
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Response" message:[[NSString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding] delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
return [[NSString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding];
}
Using Swift 3 or 4 you can access these http request for sever communication.
// For POST data to request
func postAction() {
//declare parameter as a dictionary which contains string as key and value combination. considering inputs are valid
let parameters = ["id": 13, "name": "jack"] as [String : Any]
//create the url with URL
let url = URL(string: "www.requestURL.php")! //change the url
//create the session object
let session = URLSession.shared
//now create the URLRequest object using the url object
var request = URLRequest(url: url)
request.httpMethod = "POST" //set http method as POST
do {
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // pass dictionary to nsdata object and set it as request body
} catch let error {
print(error.localizedDescription)
}
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
//create dataTask using the session object to send data to the server
let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
guard error == nil else {
return
}
guard let data = data else {
return
}
do {
//create json object from data
if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
print(json)
// handle json...
}
} catch let error {
print(error.localizedDescription)
}
})
task.resume() }
// For get the data from request
func GetRequest() {
let urlString = URL(string: "http://www.requestURL.php") //change the url
if let url = urlString {
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil {
print(error ?? "")
} else {
if let responceData = data {
print(responceData) //JSONSerialization
do {
//create json object from data
if let json = try JSONSerialization.jsonObject(with:responceData, options: .mutableContainers) as? [String: Any] {
print(json)
// handle json...
}
} catch let error {
print(error.localizedDescription)
}
}
}
}
task.resume()
}
}
// For get the download content like image or video from request
func downloadTask() {
// Create destination URL
let documentsUrl:URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL!
let destinationFileUrl = documentsUrl.appendingPathComponent("downloadedFile.jpg")
//Create URL to the source file you want to download
let fileURL = URL(string: "http://placehold.it/120x120&text=image1")
let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig)
let request = URLRequest(url:fileURL!)
let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
if let tempLocalUrl = tempLocalUrl, error == nil {
// Success
if let statusCode = (response as? HTTPURLResponse)?.statusCode {
print("Successfully downloaded. Status code: \(statusCode)")
}
do {
try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)
} catch (let writeError) {
print("Error creating a file \(destinationFileUrl) : \(writeError)")
}
} else {
print("Error took place while downloading a file. Error description: %#", error?.localizedDescription ?? "");
}
}
task.resume()
}
Objective C
Post API with parameters and validate with url to navigate if json
response key with status:"success"
NSString *string= [NSString stringWithFormat:#"url?uname=%#&pass=%#&uname_submit=Login",self.txtUsername.text,self.txtPassword.text];
NSLog(#"%#",string);
NSURL *url = [NSURL URLWithString:string];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSLog(#"responseData: %#", responseData);
NSString *str = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"responseData: %#", str);
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData
options:kNilOptions
error:nil];
NSDictionary* latestLoans = [json objectForKey:#"status"];
NSString *str2=[NSString stringWithFormat:#"%#", latestLoans];
NSString *str3=#"success";
if ([str3 isEqualToString:str2 ])
{
[self performSegueWithIdentifier:#"move" sender:nil];
NSLog(#"successfully.");
}
else
{
UIAlertController *alert= [UIAlertController
alertControllerWithTitle:#"Try Again"
message:#"Username or Password is Incorrect."
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* ok = [UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action){
[self.view endEditing:YES];
}
];
[alert addAction:ok];
[[UIView appearanceWhenContainedIn:[UIAlertController class], nil] setTintColor:[UIColor redColor]];
[self presentViewController:alert animated:YES completion:nil];
[self.view endEditing:YES];
}
JSON Response : {"status":"success","user_id":"58","user_name":"dilip","result":"You have been logged in successfully"}
Working code
**
I got the code below to call a PHP script, for some reason it say that the connection is successful but it actually didn't call my script since I haven't received the email :-(
None of the NSURLConnectionDelegate methods get called.
Testing on iPhone 5.x device and Simulator.
Any suggestions/ideas? Thank you very much!
NSString* url = [NSString stringWithFormat:#"http://www.lenniedevilliers.net/mail.php?subject=%#&to=%#&body=%#", subjectLine, toAddress, emailBody ];
NSLog(#"web service URL: %#", url);
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString: url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
connection = [[NSURLConnection alloc] initWithRequest: request delegate:self];
NSLog(#"connection: %#", [connection debugDescription]);
if (connection) {
NSLog(#"Connection succeeded");
} else {
NSLog(#"Connection failed");
}
NSString* url = [NSString stringWithFormat:#"http://www.lenniedevilliers.net/mail.php?subject=%#&to=%#&body=%#", subjectLine, toAddress, emailBody ];
NSLog(#"web service URL: %#", url);
//add the following or something like
[url setString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString: url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
//modify the following
connection = [[NSURLConnection alloc] initWithRequest: request delegate:self startImmediately:YES];
NSLog(#"connection: %#", [connection debugDescription]);
if (connection) {
NSLog(#"Connection succeeded");
} else {
NSLog(#"Connection failed");
}
I'd be willing to bet that you have some content in your email body that's not safe to send through the url
NSString* url = [NSString stringWithFormat:#"http://www.lenniedevilliers.net/mail.php?subject=%#&to=%#&body=%#", subjectLine, toAddress, emailBody ];
So say your email body contains &, that would break the code you have. You either need to escape the message body or send it through the request body instead of passing it through the URL. I could be wrong, but I bet that's what it is. Your code looks fine, I bet its the data ;)
Are you using the specific delegate functions for NSURLConnection?
- (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(#"Did Receive Response %#", response);
responseData = [[NSMutableData alloc]init];
}
- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data
{
//NSLog(#"Did Receive Data %#", data);
[responseData appendData:data];
}
- (void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error
{
NSLog(#"Did Fail");
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"Did Finish");
// Do something with responseData
}
I am having a hard time to find any examples for NSURLConnection delegate method implementations.
I want to send data with a HTTP post with a button click. Not sure how to make a "submitting" screen and "submitted". (I know how to use spinner and will use them)
I am using this code under a botton click action, but unable to use any delegate stuff. Not sure how to implement them with my current set up.
NSMutableURLRequest *request =
[[NSMutableURLRequest alloc] initWithURL:
[NSURL URLWithString:#"http://myURL.com"]];
[request setHTTPMethod:#"POST"];
NSString *postString = [wait stringByAppendingString:co];
[request setValue:[NSString
stringWithFormat:#"%d", [postString length]]
forHTTPHeaderField:#"Content-length"];
[request setHTTPBody:[postString
dataUsingEncoding:NSUTF8StringEncoding]];
//[[NSURLConnection alloc] initWithRequest:request delegate:self];
[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
[SVProgressHUD dismissWithSuccess:#"Submission Successful"];
- (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(#"Did Receive Response %#", response);
responseData = [[NSMutableData alloc]init];
}
- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data
{
//NSLog(#"Did Receive Data %#", data);
[responseData appendData:data];
}
- (void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error
{
NSLog(#"Did Fail");
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"Did Finish");
// Do something with responseData
}
You need to use the new NSURLConnectionDataDelegate protocol.
I found some exemples here:
http://blog.kemalkocabiyik.com/index.php/2012/02/fetching-data-with-getpost-methods-by-using-nsurlconnection/
And if you can read portuguese: http://www.quaddro.com.br/blog/desenvolvimento-ios/baixando-conteudo-com-nsurlconnection-e-nsurlconnectiondatadelegate-no-ios
//Connection request
-(void)requestURL:(NSString *)strURL
{
// Create the request.
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:strURL]];
// Create url connection and fire request
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
//Delegate methods
- (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(#"Did Receive Response %#", response);
responseData = [[NSMutableData alloc]init];
}
- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data
{
//NSLog(#"Did Receive Data %#", data);
[responseData appendData:data];
}
- (void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error
{
NSLog(#"Did Fail");
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"Did Finish");
// Do something with responseData
NSString *strData=[[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding];
NSLog(#"Responce:%#",strData);
}
http://codewithchris.com/tutorial-how-to-use-ios-nsurlconnection-by-example/
in this code you will use GCD ,Activity Indicator ,UIButton Action
on login button
First you will call StartActivityindicator on another thread and it keeps in moving until you remove or stop the Activityindicator.
then you will call the web service for login in GCD queue .
at the time you receive response from server call main queue to update the UI.
// After the interface declration
#interface LoginViewController ()
{
NSData *responseData;
dispatch_queue_t myqueue;
}
//Button Action
- (IBAction)Login_Button_Action:(id)sender
{
[NSThread detachNewThreadSelector: #selector(StartActivityindicator) toTarget:self withObject:nil];
myqueue =dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
dispatch_group_t group=dispatch_group_create();
dispatch_group_async(group, myqueue, ^{ [self loginWebService];});
}
-(void)loginWebService
{
//Combine Both url and parameters
NSString *UrlWithParameters = [NSString stringWithFormat:#"http://www.xxxxx.com?count=%#&user=%#&email=%#&password=%#",#"4",#"Username",s#"UserEmail",#"PAssword String"];
//Pass UrlWithParameters to NSURL
NSURL *ServiceURL =[NSURL URLWithString:UrlWithParameters];
NSMutableURLRequest *serviceRequest =[NSMutableURLRequest requestWithURL:ServiceURL];
[serviceRequest setHTTPMethod:#"POST"];
[serviceRequest setValue:#"application/json" forHTTPHeaderField:#"accept"];
[serviceRequest setValue:#"application/json" forHTTPHeaderField:#"content-type"];
//GEt Response Here
NSError *err;
NSURLResponse *response;
responseData = [NSURLConnection sendSynchronousRequest:serviceRequest returningResponse:&response error:&err];
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
NSInteger code = [httpResponse statusCode];
// check status code for response from server and do RND for code if you recive anything than 200
NSLog(#"~~~~~ Status code: %ld",(long)code);
if (code ==200)
{
// your response is here if you call right
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options: NSJSONReadingMutableContainers error: &err];
dispatch_async(dispatch_get_main_queue(),^{
// place the code here to update UI with your received response
[NSThread detachNewThreadSelector: #selector(StopActivityindicator) toTarget:self withObject:nil];
});
}
}
//Activity indicator Method to display
- (void) StartActivityindicator
{
mySpinner.hidden = NO;
[mySpinner startAnimating];
}
- (void) StopActivityindicator
{
mySpinner.hidden = YES;
[mySpinner stopAnimating];
}
I am calling NSURLConnection asynchronous method calls in my view controller. I would like to handle TWO RESPONSES FOR TWO REQUEST in the same Delegate. Please suggest me what would the best approach to achieve this? I'm developing in iOS 5 SDK.
UPDATED:
// Class A
[serverconns setDelegate:self];
connection = [serverconns executeAsyncHttpPost :firstjsonrequest];
[serverconns setDelegate:self];
connection = [serverconns executeAsyncHttpPost :secondjsonrequest];
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
}
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.appendData appendData:data];
}
- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
// logs the error
}
- (void) connectionDidFinishLoading:(NSURLConnection *)connection
{
NSData *responseData = [[NSData alloc] initWithData:appendData];
//HOW CAN WE HANDLE TWO RESPONSES FOR TWO REQUEST in the same Delegate
if (responseData)
{
// doing something
}
}
//Class B: ServerConnection
- (NSURLConnection *) executeAsyncHttpPost :(id) jsonParams
{
NSString *urlstr = [NSString stringWithFormat:#"%#", baseURL];
urlstr = [urlstr stringByAppendingFormat:method];
NSURL *pUrl = [NSURL URLWithString:urlstr];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:pUrl];
NSData *requestData = [NSData dataWithBytes:[jsonParams UTF8String] length:[jsonParams length]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-type"];
[request setHTTPBody: requestData];
return [[NSURLConnection alloc] initWithRequest:request delegate:delegateResponder startImmediately:YES];
}
-(void) setDelegate:(id)newDelegate
{
delegateResponder = newDelegate;
}
save your connections somewhere (maybe ivar of your delegate)
- (void) connectionDidFinishLoading:(NSURLConnection *)connection
{
NSData *responseData = [[NSData alloc] initWithData:appendData];
//HOW CAN WE HANDLE TWO RESPONSES FOR TWO REQUEST in the same Delegate
if (responseData)
{
if (connection == yourFirstConnection) {
// doing something for first connection
} else {
// doing something for second connection
}
}
}
just point out some minor problem of your code
NSString *urlstr = [NSString stringWithFormat:#"%#", baseURL];
urlstr = [urlstr stringByAppendingFormat:method];
should replace to
NSString *urlstr = [baseURL absoluteString];
urlstr = [urlstr stringByAppendingString:method];
and add two(or more or array) weak/assign property of NSURLConnection to your class A (connection delegate)
#property (assign) NSURLConnection *myFirstConnection;
#property (assign) NSURLConnection *mySecondConnection;
// assume only need to handle two connection otherwise NSArray should be used instead
than in your class B (create connection)
- (NSURLConnection *) executeAsyncHttpPost :(id) jsonParams
{
NSString *urlstr = [baseURL absoluteString];
urlstr = [urlstr stringByAppendingString:method];
NSURL *pUrl = [NSURL URLWithString:urlstr];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:pUrl];
NSData *requestData = [NSData dataWithBytes:[jsonParams UTF8String] length:[jsonParams length]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-type"];
[request setHTTPBody: requestData];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:delegateResponder startImmediately:YES];
delegateResponder.myFirstConnection = connection;
// delegateResponder.mSecondConnection = connection;
return connection;
}
If I were you I would create a CustomClass which inherits the NSURLConnection. And I will add property called tag.
When I initiate the CustomClass, I would set the tag property and use that to determine which request is being worked on
CustomURLConnection *connection = [[CustomURLConnection alloc] initWithRequest:request delegate:self tag:1];
- (id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate tag:(int)_tag
{
if(self = [super initWithRequest:request delegate:delegate])
{
self.tag = _tag;
}
Now in the code you posted add this
- (void) connectionDidFinishLoading:(NSURLConnection *)connection
{
NSData *responseData = [[NSData alloc] initWithData:appendData];
//HOW CAN WE HANDLE TWO RESPONSES FOR TWO REQUEST in the same Delegate
if (responseData)
{
if (connection.tag == 1){
}
}
}
return self;
}
I think all the mentioned solutions are "ugly". I would not implement a solution with delegate methods but instead create a blocks-based solution. I could post an example if you're interested. I would make use of the AFNetworking classes for this approach.
What follows is an example of a class that handles 2 different responses without using a delegate implementation, opting for blocks instead with the AFNetworking library.
- (void)JSONFromService
{
// create the first request and set the methods that handle the return values (either NSData or NSError in this case) in blocks ...
NSURL *firstURL = [NSURL URLWithString:#"http://dl.dropbox.com/u/6487838/test1.html"];
NSURLRequest *firstRequest = [NSURLRequest requestWithURL:firstURL];
AFHTTPRequestOperation *firstOperation = [[AFHTTPRequestOperation alloc] initWithRequest:firstRequest];
[firstOperation setCompletionBlockWithSuccess:^ (AFHTTPRequestOperation *operation, id object)
{
NSString *firstString = [[NSString alloc] initWithData:object encoding:NSASCIIStringEncoding];
NSLog(#"%#", firstString);
} failure:^ (AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"%#", error);
}];
[firstOperation start];
// create the second request and set the methods that handle the return values (either NSData or NSError in this case) in blocks ...
NSURL *secondURL = [NSURL URLWithString:#"http://dl.dropbox.com/u/6487838/test2.html"];
NSURLRequest *secondRequest = [NSURLRequest requestWithURL:secondURL];
AFHTTPRequestOperation *secondOperation = [[AFHTTPRequestOperation alloc] initWithRequest:secondRequest];
[secondOperation setCompletionBlockWithSuccess:^ (AFHTTPRequestOperation *operation, id object) {
NSString *secondString = [[NSString alloc] initWithData:object encoding:NSASCIIStringEncoding];
NSLog(#"%#", secondString);
} failure:^ (AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"%#", error);
}];
[secondOperation start];
}
I usually subclass NSURLConnection and add properties to store whatever context I need to handle the response.
Since the delegate methods get NSURLConnection passed in, you can just cast it back to your subclass and access the context.
Take a look at this example.
I think you should keep all of your connections in an activeConnections array. Every time one finishes, you do [activeConnections indexForObject:connection] and you update your delegate method accordingly, using the index.
Now, a cleaner way to do it( and a better way from my point of view, but this depends on how large is the data you want to transfer) is to use queues. I'll provide a small example and add comments to it:
// we assume you have 2 requests: req1, req2
//now, create a new dispatch queue
dispatch_queue_t netQueue = dispatch_queue_create("com.mycompany.netqueue",DISPATCH_QUEUE_SERIAL);
//execute the operations in the queue ASYNC
//is very important to dispatch this ASYNC on a background thread, otherwise your UI will be stuck until the request finishes
dispatch_async(netQueue,
^{
// We are on a background thread, so we won't block UI events (or, generally, the main run loop)
NSHTTPURLResponse *response = nil;
NSError *error = nil;
NSData *data = nil;
//We can call the request synchronous and block this thread until completed
data = [NSURLConnection sendSynchronousRequest:req1
returningResponse:&response
error:&error];
dispatch_async(dispatch_get_main_queue(),
^{
//call your delegate with the appropriate method for req1
//be sure to copy the contents in data, as we will reuse it with the next request
});
//We can call the other request synchronous and block this thread until completed
data = [NSURLConnection sendSynchronousRequest:req2
returningResponse:&response
error:&error];
dispatch_async(dispatch_get_main_queue(),
^{
//call your delegate with the appropriate method for req2
});
//and this can go on forever. If you have many requests to execute, simply put them in a loop
});
dispatch_release(netQueue);
Could anyone provide me with one please?
.h
#import "UntitledViewController.h"
#implementation UntitledViewController
- (id)init
{
self = [super init];
if (self)
{
NSURL *url = [NSURL URLWithString:#"http://tinyurl.com/a3cx"];
[self loadTinyURL:url];
}
return self;
}
- (void)loadTinyURL:(NSURL *)url
{
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request
delegate:self];
if (!connection)
NSLog(#"could not connect with: %#", url);
else {
NSLog(#"this works");
}
}
- (NSURLRequest *)connection:(NSURLConnection *)connection
willSendRequest:(NSURLRequest *)request
redirectResponse:(NSURLResponse *)response
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
int statusCode = [httpResponse statusCode];
// http statuscodes between 300 & 400 is a redirect ...
if (response && statusCode >= 300 && statusCode < 400)
NSLog(#"redirecting to : %#", [request URL]);
return request;
you can use NSURLConnection samplecode based on either asynchronous or synchronous from apple website.you can know why we use this delegate method through the stackoverflow link