How to submit text messages to server via ios apps - ios

my problem is I cannot send the text messages to server. Im using asihttprequest. I have define the USERNAME, UUID, PASSWORD, API_PASSWORD and NUMBER myself. What I want to do is just send the data to the server url given. Here is my code:
- (IBAction)sendClicked:(id)sender {
[sendButton resignFirstResponder];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:#"https://cc.frifon.net_dosmssend/"]];
[request setDelegate:self];
[request setNumberOfTimesToRetryOnTimeout:3];
[request setRequestMethod:#"POST"];
[request setPostValue:USERNAME forKey:#"sip"];
[request setPostValue:PASSWORD forKey:#"pwd"];
[request setPostValue:UUID forKey:#"uuid"];
[request setPostValue:API_PASSWORD forKey:#"key"];
[request setPostValue:messageText forKey:#"message"];
[request setPostValue:NUMBER forKey:#"to"];
[request setPostValue:#"Submit" forKey:#"submit"];
[request start];
nil;
[request startAsynchronous];
}
- (void)requestFinished:(ASIHTTPRequest *)request {
NSError *error = [request error];
if (!error) {
NSString *response = [request responseString];
messageText.text = response;
}
}

Try this,
- (IBAction)sendClicked:(id)sender {
[sendButton resignFirstResponder];
NSString *serviceString = https://cc.frifon.net_dosmssend/;
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:[serviceString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]]];
[request setDelegate:self];
request.requestMethod = #"POST";
request.timeOutSeconds = 30.0;
[request addPostValue:USERNAME forKey:#"sip"];
[request addPostValue:PASSWORD forKey:#"pwd"];
[request addPostValue:UUID forKey:#"uuid"];
[request addPostValue:API_PASSWORD forKey:#"key"];
[request addPostValue:messageText forKey:#"message"];
[request addPostValue:NUMBER forKey:#"to"];
[request addPostValue:#"Submit" forKey:#"submit"];
[request startAsynchronous];
}

- (IBAction)sendClicked:(id)sender {
// Add you all data in below dictionary
NSDictionary *dictionary = #{#"action":#"login",#"nick_name":nikname,#"password":pass};
NSError *error;
NSData *data = [NSJSONSerialization dataWithJSONObject:dictionary options:0 error:&error];
NSString *jason =[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"JSON summary: %#", jason);
NSString *address = [NSString stringWithFormat:#"%#",#"www.demo.com"];
address= [address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *URL = [NSURL URLWithString:address];
NSLog(#"%#",address);
// request creation
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL cachePolicy:NSURLCacheStorageAllowedInMemoryOnly
timeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPBody:data];
responseData = [[NSMutableData alloc] init];
NSURLConnection *Conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[Conn start];
}

Related

Login using Tinder API

I am using https://gist.github.com/rtt/10403467 for reference but I am not able to login into Tinder. I get a blank response.
NSURL *url = [NSURL URLWithString:#"https://api.gotinder.com/auth"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
//NSString *str = [NSString stringWithFormat:#"{\"facebook_token\": %#, \"facebook_id\": %#}",accessToken,userID];
NSDictionary *dataDict = [NSDictionary dictionaryWithObjectsAndKeys:accessToken, #"facebook_token", userID, #"facebook_id", nil];
NSData *dataFromDict = [NSJSONSerialization dataWithJSONObject:dataDict
options:NSJSONReadingAllowFragments
error:nil];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
//[request setHTTPBody:[str dataUsingEncoding:NSASCIIStringEncoding]];
[request setHTTPBody:dataFromDict];
[request setValue:#"Tinder/4.1.4 (iPhone; iOS 9.3; Scale/2.00)" forHTTPHeaderField:#"User-Agent"];
[request setValue:#"ios" forHTTPHeaderField:#"platform"];
[request setValue:#"1.0" forHTTPHeaderField:#"app-version"];
[request setValue:[NSString stringWithFormat:#"%lu",[dataFromDict length]] forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request
delegate:self];
[connection start];
Please help

How to make json post request?

I have to make json post request with the following request parameters,
{
"method":"login",
"data":{
"username":"korea",
"password":"123456"
}
}
I use the following code to make the request,
NSString *jsonRequest = [NSString stringWithFormat:#"{""\"\method:\"\login\"\"\,""\data:\"{\"\"username\":\"%#\",\"password\":\"%#\"}",username,password];
NSLog(#"Request: %#", jsonRequest);
NSURL *url = [NSURL URLWithString:#"http://myurl..."];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
I have to get the response but Im not be able to get the response
Try this
NSDictionary *objectDic = #{#"username" : username, #"password" : password};
NSDictionary *dataDic = #{#"data" : objectDic};
NSDictionary *methodDic = #{#"method" : #"login", #"data": dataDic};
NSData *requestData = [NSJSONSerialization dataWithJSONObject:methodDic
options:NSJSONWritingPrettyPrinted
error:nil];
[request setHTTPBody: requestData];

Create and send JSON data to server using Objective C

I'm trying to send JSON data to server side using POST method, but my code gives null JSON value. I am using Objective C where I fetch data from textField and convert it into string, but after that while converting this value to JSON object, it gives null value. Don't know what to do.
Here is my code:
- (IBAction)loginAction:(UIButton *)sender
{
NSString *post = [NSString stringWithFormat:#"Username=%#&Password=%#" ,self.userNameField.text,self.passwordField.text];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];
postData = [postData subdataWithRange:NSMakeRange(0, [postData length] - 1)];
NSData*jsonData = [NSJSONSerialization JSONObjectWithData:postData options:NSJSONReadingMutableContainers error:nil];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://172.31.144.227:8080/Analytics/rest/login/post"]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length" ];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:jsonData];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[theConnection start];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
}
-(void)MessagePost{
NSString * post =[NSString stringWithFormat:#"http://url.com/clients/project_id=%#&user_id=58&question=%#&send_enquiry=Send",[[self.recordchat objectForKey:#"id"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[[_txtfield text] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSLog(#"%#",post);
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:post]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postdata];
NSError *error;
NSURLResponse *response;
postdata=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *returnstring=[[NSString alloc]initWithData:postdata encoding:NSUTF8StringEncoding];
NSLog(#"String : %#",returnstring);
if (postdata){
NSDictionary *dict= [NSJSONSerialization JSONObjectWithData:postdata options:NSJSONReadingMutableContainers error:nil];
NSDictionary* latestLoans = [dict objectForKey:#"status"];
NSLog(#"Status dict = %#",latestLoans);
} else{ NSLog(#"Error while posting messages.");}}
instead of writing NSString *post = [NSString stringWithFormat:#"Username=%#&Password=%#" ,self.userNameField.text,self.passwordField.text];
you should use this
NSMutableDictionary *post = [[NSMutableDictionary alloc]init];
[post setValue:self.userNameField.text forKey:#"Username"];
[post setValue:self.passwordField.text forKey:#"Password"];
Try this -
- (IBAction)loginAction:(UIButton *)sender
{
NSDictionary *dictDetails = #{
#"Username" : self.userNameField.text,
#"Password" : self.passwordField.text
};
NSString *jsonRequest = [dict JSONRepresentation];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://172.31.144.227:8080/Analytics/rest/login/post"]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody: requestData];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)
[requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[theConnection start];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
}
Finally I wrote the correct code and it's working fine now. Please suggest me If any further modification is required..
Thank you all for your time and support..
Here is my code:
- (IBAction)loginAction:(UIButton *)sender
{
NSMutableDictionary *post = [[NSMutableDictionary alloc]init];
[post setValue:self.userNameField.text forKey:#"username"];
[post setValue:self.passwordField.text forKey:#"password"];
NSArray* notifications = [NSArray arrayWithObjects:post, nil];
NSError *writeError = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:notifications options:kNilOptions error:&writeError];
NSString *postLength = [NSString stringWithFormat:#"%d",[jsonData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://172.31.144.227:8080/Analytics/rest/login"]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length" ];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:jsonData];
NSLog(#"JSON Summary: %#", [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[theConnection start];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"Response Error= %#", response);
if ([response statusCode] >=200 && [response statusCode] <300)
{
NSData *responseData = [[NSData alloc]initWithData:urlData];
NSMutableDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil];
NSLog(#"Random Output= %#", jsonObject);
[self performSegueWithIdentifier:#"DASHBOARDSEGUE" sender:sender];
}else {
[self alertStatus:#"Connection Failed" :#"Login Failed!"];
}
}

ASIFormDataRequest returns NULL when trying to request a POST method

Hi im trying to make a POST request
my code:
NSURL *url = [NSURL URLWithString:urlString];
__weak ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setDelegate:self];
[request setRequestMethod:#"POST"];
[request setPostValue:#"JustinBieber" forKey:#"fname"];
[request setCompletionBlock:^{
NSString *result = [request responseString];
NSDictionary *dict = [result JSON];
NSLog(#"dict -%#",dict);
}];
[request setFailedBlock:^{
NSLog(#"error %#",[request error]);
}];
[request startAsynchronous];
when I run my code it returns a (null) value. My urlString is correct and the request didn't give me error also. I've tried it on web and returns a {"status":"success"} (it will return a dictionary with status successful or failed).
Use Like this. Hope this will help.
-(void)exe method
{
NSString *strURL=#"---your URL----";
NSURL *url=[NSURL URLWithString:strURL];
ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:url];
[request setRequestMethod:#"POST"];
[request setPostValue:#"JustinBieber" forKey:#"fname"];
[request setDelegate:self];
[request setTimeOutSeconds:60];
[request startAsynchronous];
}
- (void)requestFinished:(ASIHTTPRequest *)request
{
NSError *error;
if(!error)
{
NSString *receivedString = [request responseString];
NSDictionary *dic = [receivedString JSONValue];
NSLog(#"output %#",dic);
}
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
}
Try with this code -
NSURL *url = [NSURL URLWithString:urlString];
__unsafe_unretained ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setRequestMethod:#"POST"];
[request setPostValue:#"JustinBieber" forKey:#"fname"];
[request setDelegate:self];
__block id jsonData;
[request setTimeOutSeconds:300];
[request setCompletionBlock:^(){
NSError *error = nil;
NSString *responseString = (request.responseString.length)?request.responseString:#"";
NSLog(#"%#",responseString);
NSData *responseData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
jsonData = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
if(error)
completionBlock(nil, error, task);
else
completionBlock(jsonData, error, task);
}];
[request setFailedBlock:^{
completionBlock(nil, request.error, task);
}];
[request startAsynchronous];
Might be it will helpfull for you.
Did you set your headers in the script that returns JSON correctly? Assuming you're using PHP:
header('Content-Type: application/json');
The default MIME-type is "text/plain", instead of "application/json". If you dont set the MIME-type correctly you're basicly trying to parse the whole document.
So instead of:
{"status":"success"}
You are most likely trying to parse:
<html>
<head></head>
<body>{"status":"success"}</body>
</html>
-(void)exe method
{
NSString *strURL=#"---your URL----";
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:strURL]];
[request setDelegate:self];
[request setRequestMethod:#"POST"];
[request setPostValue:#"JustinBieber" forKey:#"fname"];
[request setTimeOutSeconds:60];
[request startAsynchronous];
}
- (void)requestFinished:(ASIHTTPRequest *)request
{
NSString *receivedString = [request responseString];
NSLog(#"output %#",receivedString );
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
NSString *receivedString = [request responseString];
NSLog(#"output %#",receivedString );
}

unsupported URL error code -1002

Hi Please help me how to prepare NSMutableURLRequest for below api
URL : www.XXXXXXXX.com/api.php
For Login :-
www.XXXXXXXXXXXX.com/api.php?task=login
POST Data :-
"email" => User's email
"pw" => User's Password
json response: session id on successful login
Am trying like this.
NSMutableURLRequest *request;
request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"www.XXXXXXXX.com/api.php?task=login"]];
[request setHTTPMethod:#"POST"];
NSString *postString =#"email=xxxxxxxx#gmail.com&pw=1234";
[request setValue:[NSString
stringWithFormat:#"%d", [postString length]] forHTTPHeaderField:#"Content-length"];
[request setHTTPBody:[postString
dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *connection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
One reason could be that you forgot to add the "http:" scheme:
[NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://www.XXXXXXXX.com/api.php?task=login]];
HERE --^
Note also that the correct way to set body data and in particular the length is
NSString *postString =#"email=xxxxxxxx#gmail.com&pw=1234";
NSData *postData = [postString dataUsingEncoding:NSUTF8StringEncoding];
[request setValue:[NSString stringWithFormat:#"%d", [postData length]]
forHTTPHeaderField:#"Content-length"];
[request setHTTPBody:postData];
because the length of the UTF-8 encoded data can be different from the (Unicode) string length.
I ran into this error when I specified my base URL with a variable that accidentally contained a new line.
Try this:
NSError *error;
NSString *jsonString;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonData1
options:0 error:&error];
if (!jsonData) {
NSLog(#"Got an error: %#", error);
} else {
jsonString= [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
NSData *postData = [[[NSString alloc] initWithFormat:#"method=methodName&email=%#&password=%#", user_name, pass_word] dataUsingEncoding:NSUTF8StringEncoding];
NSString *postLength = [NSString stringWithFormat:#"%ld",[postData length]];
jsonData=[jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:URL]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"\"Accept\""];
[request setValue:#"application/json" forHTTPHeaderField:#"\"Content-Type\""];
[request setValue:postLength forHTTPHeaderField:#"\"Content-Length\""];
[request setValue:#"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:jsonData];
NSError *requestError = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&requestError];
if ([response statusCode] >= 200 && [response statusCode] < 300) {
NSError *serializeError = nil;
NSString* newStr = [NSString stringWithUTF8String:[urlData bytes]];
NSDictionary *jsonData = [NSJSONSerialization
JSONObjectWithData:urlData
options:NSJSONReadingAllowFragments
error:&serializeError];
NSLog(#"recdata %#",jsonData);
}
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection)
{
NSLog(#"theConnection is succesful");
}
[connection start];

Resources