I am using the following code to upload some images to server. I would like to implement the UIProgressbar. I wrote the connection didSendBody method. The thing is that, for some requests, the delegate method is working. But for the request where I upload image, the method is not called. Please help me in this.
-(void)performRequestWithPost:(NSData*)postData withURL:(NSString*)baseUrl forType:(NSString*)type contentType:(NSString*)contentType
{
if ([self internetAvailable] == YES) {
NSURL *theURL = [NSURL URLWithString:baseUrl];
NSMutableURLRequest *theRequest = [[NSMutableURLRequest alloc] init] ;
[theRequest setURL:theURL];
[theRequest setHTTPMethod:#"POST"];
[theRequest setValue:contentType forHTTPHeaderField:#"Content-Type"];
[theRequest setHTTPBody:postData];
[NSURLConnection connectionWithRequest:theRequest delegate:self];
[NSURLConnection sendAsynchronousRequest:theRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
{
if(!connectionError)
{
NSString *theResponseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] ;
NSError *error;
NSData *jsonData = [theResponseString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableDictionary *responseDict = [NSMutableDictionary dictionaryWithDictionary:[NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error]];
[responseDict setObject:type forKey:#"type"];
NSLog(#"theResponseString-%#",responseDict);
if (self.delegate && [self.delegate respondsToSelector:#selector(serverDidRecieveResponse:)])
[self.delegate serverDidRecieveResponse:responseDict];
}
}];
}
else
{
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"No Internet" message:#"Check your Connection." delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
});
}
}
-(void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite
{
if([self.delegate respondsToSelector:#selector(progressViewProgress:)])
{
NSLog(#"bytesWritten: %uld, totalBytesWritten: %uld, totalBytesExpectedToWrite: %uld",bytesWritten,totalBytesWritten,totalBytesExpectedToWrite);
[self.delegate progressViewProgress:(float)(totalBytesWritten/totalBytesExpectedToWrite)];
}
}
Note: I have added the NSURLConnectionDataDelegate. Also the image upload is success all the time.
Related
hi I am new to iOS and I am giving request to server and getting top to the mobile number and through request reply I am able to get the otp but when I print the data out of the seesion which is initialised inside block I am getting null
this is my .h file
#import <UIKit/UIKit.h>.
#interface OtpViewController : UIViewController
#property (nonatomic,strong) NSString *str;
#property (strong,nonatomic) NSString *tmp;
#property(weak,nonatomic) NSString *requestReply ;
#end
this is my url request block in .m file
- (IBAction)submitb:(id)sender
{
if (_mobiletf.text && _mobiletf.text.length >0 )
{
/* not empty - do something */
NSString *post = [NSString stringWithFormat:#"phone=%#",_mobiletf.text];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
// Next up, we read the postData's length, so we can pass it along in the request.
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
// Now that we have what we'd like to post, we can create an NSMutableURLRequest, and include our postData
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://www.sitesandflats.com/send_otp.php"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSLog(#"the data Details is %#", post);
// And finally, we can send our request, and read the reply by creating a new NSURLSession:
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; // this is json string
// NSError *error;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error]; // you need to convert to dictionary object
NSLog(#"requestReply: %#", jsonDict);
self.tmp=[jsonDict valueForKey:#"otp"] ;
self.str=self.tmp;
NSLog(#"tmp storage inside block:%#",self.tmp);
[self performSelector:#selector(updateStatus) withObject:nil afterDelay:1.0];
// NSLog(#"requestReply: %#", jsonDict);
//self.tmp=[jsonDict valueForKey:#"otp"] ;
//self.str=self.tmp;
//NSLog(#"tmp storage inside block:%#",self.tmp);
}] resume];
//self.str=self.tmp;
NSLog(#" storage:%#",self.str);
NSLog(#"tmp storage:%#",self.tmp);
[ self performSegueWithIdentifier:#"b1" sender:self];
}
else
{
/* what ever */
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:#"Please check your input!!."
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
}
-(void)updateStatus{
NSLog(#" storage:%#",self.str);
NSLog(#"tmp storage:%#",self.tmp);
// [ self performSegueWithIdentifier:#"b1" sender:self];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(nullable id)sender
{
VerifyViewController *loadCtr = (VerifyViewController *)segue.destinationViewController;
loadCtr.otpStr =self.tmp;
loadCtr.mobileStr = _mobiletf.text;
}
this is my print log
2017-06-01 12:44:08.813 MenuBar[2750:135123] the data Details is phone=9047038606
2017-06-01 12:44:08.829 MenuBar[2750:135123] 9047038606
2017-06-01 12:44:08.835 MenuBar[2750:135123] storage:(null)
2017-06-01 12:44:08.836 MenuBar[2750:135123] tmp storage:(null)
2017-06-01 12:44:10.122 MenuBar[2750:135162] requestReply: {
otp = 552749;
success = 1;
}
2017-06-01 12:44:10.122 MenuBar[2750:135162] tmp storage inside block:552749
block is the additional thread , so you need to wait for completion block, so change your code like below
if you want to acces the data in outside
- (IBAction)submitb:(id)sender
{
if (_mobiletf.text && _mobiletf.text.length >0 )
{
/* not empty - do something */
NSString *post = [NSString stringWithFormat:#"phone=%#",_mobiletf.text];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
// Next up, we read the postData's length, so we can pass it along in the request.
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
// Now that we have what we'd like to post, we can create an NSMutableURLRequest, and include our postData
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://www.sitesandflats.com/send_otp.php"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSLog(#"the data Details is %#", post);
// And finally, we can send our request, and read the reply by creating a new NSURLSession:
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; // this is json string
// NSError *error;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error]; // you need to convert to dictionary object
NSLog(#"requestReply: %#", jsonDict);
self.tmp=[jsonDict valueForKey:#"otp"] ;
self.str=self.tmp;
NSLog(#"tmp storage inside block:%#",self.tmp);
[self updateStatus];
}] resume];
}
else
{
/* what ever */
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:#"Please check your input!!."
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
}
-(void)updateStatus{
NSLog(#" storage:%#",self.str);
NSLog(#"tmp storage:%#",self.tmp);
dispatch_async(dispatch_get_main_queue(), ^{
[ self performSegueWithIdentifier:#"b1" sender:self];
});
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(nullable id)sender
{
VerifyViewController *loadCtr = (VerifyViewController *)segue.destinationViewController;
loadCtr.otpStr =self.tmp;
loadCtr.mobileStr = _mobiletf.text;
}
I am trying to get connection from server and receive response from server but I can't understand for the response code.
NSString *post = [NSString stringWithFormat:#"Username=%#&Password=%#",#"_username",#"_password"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"https://<MY_URL>"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
if(conn) {
NSLog(#"Connection Successful");
} else {
NSLog(#"Connection could not be made");
}
this is correct or not because I am not getting a response .??
now what is code for response?????
NSURLResponse *response=nil;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
NSLog(#"%#",response);
if (response) {
//UIStoryboard *story=[UIStoryboard storyboardWithName:#"Main" bundle:nil];
//TableViewController *obj=[story instantiateViewControllerWithIdentifier:#"table1"];
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Login success" message:#"correct Username or Password" delegate:self cancelButtonTitle:#"Done" otherButtonTitles: nil];
[alert show];
//[self.navigationController pushViewController:obj animated:YES];
}
else
{
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Login Failure" message:#"Incorrect Username or Password" delegate:self cancelButtonTitle:#"Done" otherButtonTitles: nil];
[alert show];
}
You need to fetch that data:
NSError *error = nil;
NSURLResponse *response = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if(responseData) {
NSDictionary *results = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments error:&error];
NSLog(#"res---%#", results);
}
and use dictionary for further use.
ALL the code is correct only you need to add the this in your info.plist
App Transport Security Setting
Allow arbitrary Loads
I want to post Dictionary to a Web service. but it is not getting post .Every time when i post data i am getting error message form web-service. I also try different approach using AFNetworking but using that approach i am getting 406 error.
you can see the other question here
NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
[params setValue:self.txtUserName.text forKey:#"name"];
[params setValue:self.txtEmail.text forKey:#"mail"];
[params setValue:self.txtPass.text forKey:#"conf_mail"];
[params setValue:self.txtPass2.text forKey:#"pass"];
NSData *body=[NSKeyedArchiver archivedDataWithRootObject:params];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://web.info/ministore/store-commerce/user/register"]];
[request setHTTPBody:body];
[request setHTTPMethod:#"POST"];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue currentQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
{
if (connectionError){
NSLog(#"Error: %#", connectionError);
[ProgressHUD dismiss];
}
else {
NSLog(#"data as String: %#", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
NSError *e = nil;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: data options:NSJSONReadingMutableContainers error:&e];
NSMutableDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
NSMutableDictionary *dict1=[dict objectForKey:#"data"];
NSLog(#"data -- %#",[dict objectForKey:#"data"]);
NSLog(#"status -- %#",[dict objectForKey:#"status"]);
int num=[[dict valueForKey:#"status"]intValue];
if( num== 0)
{
NSString *strMail=[dict1 valueForKey:#"mail"];
NSString *strName=[dict1 valueForKey:#"name"];
NSString *strPass=[dict1 valueForKey:#"pass"];
if(strMail.length==0)
{
strMail=#"";
}
if(strName.length==0)
{
strName=#"";
}
if(strPass.length==0)
{
strPass=#"";
}
NSString *Message=[NSString stringWithFormat:#"Please correct the follwing \n %# \n %#\n %# ",strMail,strName,strPass];
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Error" message:Message delegate:nil cancelButtonTitle:#"ok" otherButtonTitles:nil];
[alert show];
}
else
{
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:nil message:[NSString stringWithFormat:#"%#",[dict1 objectForKey:#"message"]] delegate:nil cancelButtonTitle:#"ok" otherButtonTitles:nil];
[alert show];
}
if (!jsonArray) {
NSLog(#"Error parsing JSON: %#", e);
}
[ProgressHUD dismiss];
}
}];
The body you posted generated by NSData *body=[NSKeyedArchiver archivedDataWithRootObject:params]; is NSPropertyListBinaryFormat_v1_0 which is a binary serialize data.
Http server could not recognise it. You can POST by JSON
NSData *body = [NSJSONSerialization dataWithJSONObject:"NSDictionary variable name"
options:NSJSONWritingPrettyPrinted
error:&error];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://web.info/ministore/store-commerce/user/register"]];
[request setHTTPBody:body];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-type"];
[request setValue:[NSString stringWithFormat:#"%d", [body length]] forHTTPHeaderField:#"Content-Length"];
I am using JSON to get data from web service.The problem is When i call web service and due to slow response my app become unresponsive for few seconds and some times crash.
I search a lot and found that by making Asynchronous call instead of Synchronous call can solve problem. But how to use asynchronous call that i don't know.
My code is like..
SBJSON *json = [SBJSON new];
json.humanReadable = YES;
responseData = [[NSMutableData data] retain];
NSString *service = #"/Get_NearbyLocation_list";
double d1=[[[NSUserDefaults standardUserDefaults]valueForKey:#"LATITUDE"] doubleValue];
NSLog(#"%f",d1);
double d2=[[[NSUserDefaults standardUserDefaults]valueForKey:#"LONGITUDE"] doubleValue];
NSLog(#"%f",d2);
NSString *requestString = [NSString stringWithFormat:#"{\"current_Lat\":\"%f\",\"current_Long\":\"%f\"}",d1,d2];
NSLog(#"request string:%#",requestString);
// NSString *requestString = [NSString stringWithFormat:#"{\"GetAllEventsDetails\":\"%#\"}",service];
NSData *requestData = [NSData dataWithBytes: [requestString UTF8String] length: [requestString length]];
NSString *fileLoc = [[NSBundle mainBundle] pathForResource:#"URLName" ofType:#"plist"];
NSDictionary *fileContents = [[NSDictionary alloc] initWithContentsOfFile:fileLoc];
NSString *urlLoc = [fileContents objectForKey:#"URL"];
urlLoc = [urlLoc stringByAppendingString:service];
NSLog(#"URL : %#",urlLoc);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: urlLoc]];
NSString *postLength = [NSString stringWithFormat:#"%d", [requestData length]];
[request setHTTPMethod: #"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody: requestData];
// self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
NSError *respError = nil;
NSData *returnData= [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: &respError ];
if (respError)
{
UIAlertView *alt=[[UIAlertView alloc]initWithTitle:#"Internet connection is not Available!" message:#"Check your network connectivity" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alt performSelectorOnMainThread:#selector(show) withObject:nil waitUntilDone:YES];
[alt release];
[customSpinner hide:YES];
[customSpinner show:NO];
}
else
{
NSString *responseString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];
NSLog(#" %#",responseString);
NSDictionary *results = [[responseString JSONValue] retain];
NSLog(#" %#",results);
thanks in advance..
NSData *returnData= [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: &respError ];
this line makes the call a synchronous one.
Use this
-(void)downloadWithNsurlconnection
{
//MAke your request here and to call it async use the code below
NSURLConnection * connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES];
}
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
[receivedData setLength:0];
}
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[receivedData appendData:data];
}
- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
- (NSCachedURLResponse *) connection:(NSURLConnection *)connection willCacheResponse: (NSCachedURLResponse *)cachedResponse {
return nil;
}
- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"Succeeded! Received %d bytes of data",[receivedData length]);
//Here in recieved data is the output data call the parsing from here and go on
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
this is how u can send asynchronous url request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: urlLoc]];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
if ([data length] > 0 && error == nil)
//date received
else if ([data length] == 0 && error == nil)
//date empty
else if (error != nil && error.code == ERROR_CODE_TIMEOUT)
//request timeout
else if (error != nil)
//error
}];
I am trying to post some data to the web service using JSON POST method, I have tried so many ways to do this, but none is working. Here is my code, please check:
NSArray *objects=[NSArray arrayWithObjects:#"value1", #"value2",#"value3", #"value4",#"value5", #"value6",#"value7", #"value8",#"value9", nil] ;
NSArray *keys=[NSArray arrayWithObjects:#"FirstName", #"LastName",#"UserName", #"Password",#"Email", #"Gender",#"DeviceId", #"DeviceName",#"ProfileImage", nil];
NSData *_jsonData=nil;
NSString *_jsonString=nil;
NSURL *url=[NSURL URLWithString:urlstring];
NSDictionary *JsonDictionary=[NSDictionary dictionaryWithObjects:objects forKeys:keys];
if([NSJSONSerialization isValidJSONObject:JsonDictionary]){
_jsonData=[NSJSONSerialization dataWithJSONObject:JsonDictionary options:0 error:nil];
_jsonString=[[NSString alloc]initWithData:_jsonData encoding:NSUTF8StringEncoding];
}
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
// [request setHTTPBody:_jsonData];
// [request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
// [request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
// [request setValue:[NSString stringWithFormat:#"%d", [_jsonData length]] forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSString *finalString = [_jsonString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
[request setHTTPBody:[finalString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]];
// //return and test
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
Please check.
Here is a sample code am trying to register a user.
In the 'Register' button click,write the following code:
- (IBAction)registerButtonPressed:(id)sender
{
BOOL valid = FALSE;
valid=[self validateEntry];
if(valid)
{
NSString *bytes = [NSString stringWithFormat:#"{\"UserName\":\"%# %#\",\"Email\":\"%#\",\"UserType\":\"normaluser\",\"Password\":\"%#\"}",firstName,lastName,email,password];
NSURL *url=[NSURL URLWithString:urlstring];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:[bytes dataUsingEncoding:NSUTF8StringEncoding]];
[self setUrlConnection:[NSURLConnection connectionWithRequest:request delegate:self]];
[self setResponseData:[NSMutableData data]];
[self.urlConnection start];
}
}
Then add the following as Connection delegate methods:
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[self.responseData setLength:0];
}
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.responseData appendData:data];
}
- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Network Status"
message:#"Sorry,Network is not available. Please try again later."
delegate:self cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[alert show];
}
- (void) connectionDidFinishLoading:(NSURLConnection *)connection
{
if (connection == self.urlConnection)
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSError *error;
NSDictionary *jsonString=[NSJSONSerialization JSONObjectWithData:self.responseData options:kNilOptions error:&error];
if(jsonString != nil)
{
if ([[[jsonString objectForKey:#"data"] objectForKey:#"id"] length])
{
[[NSUserDefaults standardUserDefaults] setValue:[[jsonString objectForKey:#"data"] objectForKey:#"id"] forKey:#"user_id"];
[[NSUserDefaults standardUserDefaults] setValue:[[jsonString objectForKey:#"data"] objectForKey:#"UserName"] forKey:#"user_name"];
[[NSUserDefaults standardUserDefaults] synchronize];
[delegate userRegistrationViewControllerResponse:self];
}
else
{
UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:#"Info" message:[jsonString objectForKey:#"statusText"] delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alertView show];
}
}
else
{
UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:#"Server Busy" message:#"Register after sometime" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alertView show];
}
}
}
This will post the user information as JSON.
Try this one....
NSURL *aUrl = [NSURL URLWithString:#"https://www.website.com/_api/Login/"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:0.0];
[request setHTTPMethod:#"POST"];
NSString *postString = [NSString stringWithFormat:#"EmailAddress=%#&UserPassword=%#",uName.text,pwd.text];
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
-Than call the NSURLConnection delegate methods.. dot forgot to alloc the responseData....
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
responseData = nil;
json =[[responseString JSONValue] retain];
NSLog(#"Dict here: %#", json);
}
The request should be something along these lines...
NSURL * url = [NSURL URLWithString:#"your_url"];
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSError * error = nil;
NSData * postData = [NSJSONSerialization dataWithJSONObject:your_json_dictionary_here options:NSJSONReadingMutableContainers error:&error];
[request setHTTPBody:postData];
I also suggest to check your response to find out why is your request failing. Is it on the client side or server side (and why?)...