Sending SMS via Twilio on ios? - iphone

How can i send SMS through twilio, i have tried already and doing following.
- (IBAction)sendButtonPressed:(id)sender
{
NSLog(#"Sending request.");
// Common constants
NSString *kTwilioSID = delegate.sessionId;
NSString *kTwilioSecret = delegate.twilioToken;
NSString *kFromNumber = delegate.twlioNumber;
NSString *kToNumber = #"+14126620408";
NSString *kMessage = #"Hi there......";
// Build request
NSString *urlString = [NSString stringWithFormat:#"https://%#:%##api.twilio.com/2010-04-01/Accounts/%#/SMS/Messages", kTwilioSID, kTwilioSecret, kTwilioSID];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
// Set up the body
NSString *bodyString = [NSString stringWithFormat:#"From=%#&To=%#&Body=%#", kFromNumber, kToNumber, kMessage];
NSData *data = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:data];
NSError *error;
NSURLResponse *response;
NSData *receivedData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
// Handle the received data
if (error) {
NSLog(#"Error: %#", error);
} else {
NSString *receivedString = [[NSString alloc]initWithData:receivedData encoding:NSUTF8StringEncoding];
NSLog(#"Request sent. %#", receivedString);
}
}
and got error: The operation couldn’t be completed. (kCFErrorDomainCFNetwork error -1012.
Please help to do this issue, or share with me any helping meterial. Thanks in Advance.

According to this answer, error 1012 means that a request for authentication was canceled by the user.
It's just a hunch, but you may want to try using HTTP Basic Auth by adding an Authorization header like this: Objective-c HTTP Basic authentication instead of including the credentials in the URL string, which counts on the Objective C library to turn those into a header correctly.

Make sure that the HttpPost param is URL-encoded, so you should change
NSString *kToNumber = #"+14126620408";
to
NSString *kToNumber = #"%2B14126620408";

I've written this blog post to help you get this done quickly using Xcode 8 and Swift 3.
https://www.twilio.com/blog/2016/11/how-to-send-an-sms-from-ios-in-swift.html
Using a server-side language of your choosing and Alamofire for HTTP requests, the request boils down to this:
#IBAction func sendData(sender: AnyObject) {
let headers = [
"Content-Type": "application/x-www-form-urlencoded"
]
let parameters: Parameters = [
"To": phoneNumberField.text ?? "",
"Body": messageField.text ?? ""
]
Alamofire.request("YOUR_NGROK_URL/sms", method: .post, parameters: parameters, headers: headers).response { response in
print(response)
}
}

#IBAction func sendData(sender: AnyObject) {
let headers = [
"Content-Type": "application/x-www-form-urlencoded"
]
let parameters: Parameters = [
"To": "enter your number",
"Body": "enter your text"
]
Alamofire.request("YOUR_NGROK_URL/sms", method: .post, parameters: parameters, headers: headers).response { response in
print(response)
}
}
you must be installed
TIP: pod 'Alamofire', '~> 5.2'

Related

DocuSign API SetBody Objective C

I'm trying to use a service of DocuSign API in an objective C project. This link shows what data I've to add to body but I'm still starting with objective C development and I can't know how do it.
I tried the following but I received nil data
NSDictionary *EnvelopesStatusRequestData = #{#"envelopeIds": envelopesPending};
where envelopesPending is an array that I fill with envelopesId that I have in a DDBB.
NSMutableArray *envelopesPending = [NSMutableArray array];
This is the code that I use to call service API:
NSDictionary *authenticationHeader = #{ #"Username": email, #"Password" : password, #"IntegratorKey" : integratorKey };
NSDictionary *EnvelopesStatusRequestData = #{#"envelopeIds": envelopesPending};
NSData* dataStatus = [[self jsonStringFromObject:EnvelopesStatusRequestData] dataUsingEncoding:NSUTF8StringEncoding];
NSString *envelopesURL = [NSMutableString stringWithFormat:#"%#/envelopes/status",baseUrl];
NSMutableURLRequest *envelopeRequest = [self initializeRequest:envelopesURL setMethod:#"GET" setBody:dataStatus];
[envelopeRequest setValue:[self jsonStringFromObject:authenticationHeader] forHTTPHeaderField:#"X-DocuSign-Authentication"];
[envelopeRequest setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSURLResponse *envelopesResponse = nil;
NSError *envelopesError = nil;
NSData *envelopeData = [NSURLConnection sendSynchronousRequest:envelopeRequest returningResponse:&envelopesResponse error:&envelopesError];
EDIT:
The error was that is a PUT method, so the request is:
NSMutableURLRequest *envelopeRequest = [self initializeRequest:envelopesURL setMethod:#"PUT" setBody:dataStatus];
With this change I have an error that says:
errorCode = "INVALID_REQUEST_PARAMETER";
message = "The request contained at least one invalid parameter. Query parameter 'from_date' must be set to a valid DateTime, or 'envelope_ids' or 'transaction_ids' must be specified.";
This error is solved adding the envelope_ids parameter to request:
PUT https://{server}/restapi/{apiVersion}/accounts/{accountId}/envelopes/status?envelope_ids=request_body
I pass the dictionary to a string with this code:
NSData *dataEnv = [NSJSONSerialization dataWithJSONObject:envelopesPending options:NSJSONReadingMutableLeaves error:&error];
NSString *querystring = [[NSString alloc] initWithData:dataEnv encoding:NSUTF8StringEncoding];
querystring = [querystring stringByReplacingOccurrencesOfString:#"[" withString:#""];
querystring = [querystring stringByReplacingOccurrencesOfString:#"]" withString:#""];
querystring = [querystring stringByReplacingOccurrencesOfString:#"\"" withString:#""];
NSString *envelopesURL = [NSMutableString stringWithFormat:#"%#/envelopes/status?envelope_ids=%#",baseUrl, querystring];
It looks like you've figured this out, but basically here are the details of the REST API call you need to make:
Get Envelope Status for more than One Envelope
This returns envelope status for the requested envelopes.
URL:
/accounts/{accountId}/envelopes/status
Formats:
XML, JSON
HTTP Method:
PUT
Required URL Parameter:
?envelope_ids=request_body
Request Body:
{
"envelopeIds":[
"String content",
"String content"
],
}
So a sample request would look like:
PUT https://{server}/restapi/{apiVersion}/accounts/{accountId}/envelopes/status?envelope_ids=request_body
X-DocuSign-Authentication: <DocuSignCredentials><Username>{name}</Username><Password>{password}</Password><IntegratorKey>{integrator_key}</IntegratorKey></DocuSignCredentials>
Accept: application/json
Content-Type: application/json
{
"envelopeIds":[
"12af49cd-....................",
"b342c324-...................."
],
}
The error was that is a PUT method, so the request is:
NSMutableURLRequest *envelopeRequest = [self initializeRequest:envelopesURL setMethod:#"PUT" setBody:dataStatus];
With this change I have an error that says:
errorCode = "INVALID_REQUEST_PARAMETER"; message = "The request contained at least one invalid parameter. Query parameter 'from_date' must be set to a valid DateTime, or 'envelope_ids' or 'transaction_ids' must be specified.";
This error is solved adding the envelope_ids parameter to request:
PUT https://{server}/restapi/{apiVersion}/accounts/{accountId}/envelopes/status?envelope_ids=request_body
I pass the dictionary to a string with this code:
NSData *dataEnv = [NSJSONSerialization dataWithJSONObject:envelopesPending options:NSJSONReadingMutableLeaves error:&error];
NSString *querystring = [[NSString alloc] initWithData:dataEnv encoding:NSUTF8StringEncoding];
querystring = [querystring stringByReplacingOccurrencesOfString:#"[" withString:#""];
querystring = [querystring stringByReplacingOccurrencesOfString:#"]" withString:#""];
querystring = [querystring stringByReplacingOccurrencesOfString:#"\"" withString:#""];
NSString *envelopesURL = [NSMutableString stringWithFormat:#"%#/envelopes/status?envelope_ids=%#",baseUrl, querystring];

iOS Unable to store URL contents into array

I have to connect to a URL to check whether the records is empty. The response looks something like this:
<?xml version = "1.0" encoding = "UTF-8"?>
<find>
<record_id>1234</record_id>
<no_record>00001</no_record>
<entry_num>00001</entry_num>
<session-id>aijheifaohqrihelrkqn324tlejaofjaf</session-id>
</find>
My codes:
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init]
autorelease];
[request setURL:[NSURL URLWithString: finalSearchURL]];
// Content-Type related.
[request setValue:#"application/x-www-form-urlencoded"
forHTTPHeaderField:#"Content-Type"];
// Create Connection.
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (conn) {
// The connection was established.
NSMutableData *receivedData = [[NSMutableData alloc] initWithContentsOfURL:[NSURL URLWithString:request]];
NSLog( #"Data will be received from URL: %#", request.URL );
NSLog(#"Recieved Data 2: %#", receivedData);
}
else
{
// The download could not be made.
NSLog( #"Data could not be received from: %#", request.URL );
}
But it returns me:
Recieved Data : <3c3f786d 6c207665 7273696f 6e203d20 22312e30 2220656e 636f6469 6e67203d 20225554 462d3822 3f3e0a3c 66696e64 3e0a3c73 65745f6e 756d6265 723e3031 39303633 3c2f7365 745f6e75 6d626572 3e0a3c6e 6f5f7265 636f7264 733e3030 30303030 3030313c 2f6e6f5f 7265636f 7264733e 0a3c6e6f 5f656e74 72696573 3e303030 30303030 30313c2f 6e6f5f65 6e747269 65733e0a 3c736573 73696f6e 2d69643e 4d505843 33323433 58564336 4534454a 41464232 45473541 39374237 584e3832 43554631 4e314234 584e4c37 424c5947 4e533c2f 73657373 696f6e2d 69643e0a 3c2f6669 6e643e0a 20>
Can anyone help to tell me what am I doing wrong? This is my first attempt for getting response from a url please help thanks!
See the data as a string this way:
NSString *string = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
NSLog(#"the xml string is %#", string);
If the parsing goal is simple enough - like just to find the value of one tag - you can use string methods to parse. Otherwise, NSXMLParser or several other options are available.
To see if the string contains a substring, you can do something like this:
if (string) {
NSRange range = [string rangeOfString:#"<session-id>"];
if (range.location != NSNotFound) {
// session-id tag is at index range.location, so we know it's there
}
}
The method you used is to get the raw data from the url. You need a parser to convert the raw data to the understandable structure (probably NSDictionary rather than NSArray).
Apple has provided NSXMLParser for you to retrieve the xml structure from the url or you can find other xml parser libraries.
Actually, your code is returning the correct data. Since NSData can hold any kind of data, it will just display the hex value. If you convert the hex data to a sting, you'll see that it has the correct text.
Now, your code can be simplified a lot. All the code for setting up the NSURLConnection is not needed at all. All you need is the following line.
NSString *recievedText = [NSString stringWithContentsOfFile:finalSearchURL encoding:NSUTF8StringEncoding error:NULL];

How to avoid URL NOT SUPPORTED error on iphone

I am calling a URL through POST HTTP method. When I am not connected to 3G or WiFi, it will never fetch the URL correctly and will never get the response from the URL correctly.
Connection is made through post:
NSString *URL = [NSString stringWithFormat:#"http://www.abc.com/webservices/client_server.cfc];
[[NSURLCache sharedURLCache] removeAllCachedResponses];
NSString *time_stamp =[NSString stringWithFormat:#"time_stamp=%#", self.today];
NSData *postData = [time_stamp dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *URLRequest = [[[NSMutableURLRequest alloc] init] autorelease];
[URLRequest setURL:[NSURL URLWithString:URL]];
[exhURLRequest setHTTPMethod:#"POST"];
[URLRequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[URLRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[URLRequest setHTTPBody:postData];
self.connection =[[[NSURLConnection alloc] initWithRequest:URLRequest delegate:self] autorelease];
NSAssert(self.connection != nil, #"Failure to create URL connection.");
I am checking if I get the response through :
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
// check for HTTP status code for proxy authentication failures
// anything in the 200 to 299 range is considered successful
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if (([httpResponse statusCode]/100) == 2) {
self.data = [NSMutableData data];
} else {
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:
NSLocalizedString(#"HTTP Error",
#"Error message displayed when receving a connection error.")
forKey:NSLocalizedDescriptionKey];
NSError *error = [NSError errorWithDomain:#"HTTP" code:[httpResponse statusCode] userInfo:userInfo];
[self handleError:error];
}
}
But some how when the URL is not connected lets say when I am in the metro or something, I cannot connect to URL and it throws me "URL NOT SUPPORTED". How can I avoid such a scenario and allow the app to push forward without throwing such an error ? If anybody has used offline redirection to the app without keep on waiting the user on the front screen.
Download apple’s Reachability sample code. Add Reachability.h+.m to your project. Link SystemConfiguration framework. Then use their Reachability class like so.
#import "Reachability.h"
for WiFi:
-(void)doStuff{
Reachability *wifi = [Reachability reachabilityForLocalWiFi];
if (wifi.currentReachabilityStatus == ReachableViaWiFi){
// do connected stuff
}
else {
// do offline stuff
}
}
For Wifi or 3G:
-(void)doStuff{
NetworkStatus connectivity = [Reachability reachabilityForInternetConnection].currentReachabilityStatus;
if (connectivity == ReachableViaWiFi || connectivity == ReachableViaWWAN){
// do connected stuff
}
else {
// do offline stuff
}
}
If you will be continually doing network tasks add the reachability object to your class. That will improve performance and allow you to use it's notifier.
some time this "URL NOT SUPPORTED error" is due to the url not encoding.
for this encode url by using this.or there are lots of ways on internet.
dont encode whole url or base url (as it will encode ":" and '/' too and it may cause errors)
only special charecter needs to be encode like &,# etc.
NSString *encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(
NULL,
(CFStringRef)pathRequest,
NULL,
(CFStringRef)#"!*'();:#&=+$,%#[]",
kCFStringEncodingUTF8 ));
How to check for an active Internet connection on iOS or OSX?
Use the solution propsed here to avoid sending a request when you don't have an active internet connection. Simple.

iPhone posting xml to ASP.net MVC webservices

Is it possible to POST XMLData to the webservices from iPhone OS. The webservices are developed in ASP.net MVC 3.0 with RESTFul url and we would like iPhone developers to send input data in XML format as POST variable..
The webservice actionresult looks like the following where sightings is the parameter that is expected to pass as POST variable
public ActionResult Update(XDocument sightings)
{
try
{
XMLHelper xmlHelper = new XMLHelper();
}
}
That's definitely applicable all you need to do is to use NSMutableURLRequest as the following:
NSString* sXMLToPost = #"<?xml version=\"1.0\"?><Name>user</Name>";
NSData* data = [sXMLToPost dataUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:#"http://myurl.com/RequestHandler.ashx"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:[sXMLToPost dataUsingEncoding:NSUTF8StringEncoding]];
NSURLResponse *response;
NSError *error;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
if (error) {
//handle the error
}
And Now in your ASHX file parse the InputStream to read the posted XML:
System.IO.Stream str; String strmContents;
Int32 counter, strLen, strRead;
str = Request.InputStream;
strLen = Convert.ToInt32(str.Length);
byte[] strArr = new byte[strLen];
strRead = str.Read(strArr, 0, strLen);
// Convert byte array to a text string.
strmContents = "";
for (counter = 0; counter < strLen; counter++)
{
strmContents = strmContents + strArr[counter].ToString();
}
Remember you can always check the request type using:
if (context.Request.RequestType == "POST")
MSDN HttpRequest.InputStream

iphone SDK:How use URL to post data back?

I read a plist data at LightTableViewController.m
and I load a data like this :
LOG RESULT:
The Plist Data Is : (
{
category = 11;
id = 1;
name = "LIVING RM";
status = 0;
},
{
category = 11;
id = 2;
name = "BEDROOM RM";
status = 0;
}
)
I need to post the "id" and "status" back to the database
to control which light to turn on or turn off
And this part is the my post method,It's in LightCell0.m
- (void)switchToggled:(id)sender {
UISwitch *theSwitch = (UISwitch *)sender;
UITableViewCell *cell = (UITableViewCell *)theSwitch.superview.superview;
UITableView *tableView = (UITableView *)cell.superview;
NSIndexPath *indexPath = [tableView indexPathForCell:cell];
if(theSwitch.on) {
NSURL * url;
NSMutableURLRequest * request;
NSString *_urlString = #"http://10.85.28.99/req_light.php";
url = [self smartURLForString:_urlString];
request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
//This is my first post method,it is static,only get the indexPath,Not a real id and status I want to post back
NSString *post = [NSString stringWithFormat:#"lightcb%i=1", indexPath.row+1];
NSData *postData = [ NSData dataWithBytes: [ post UTF8String ] length: [ post length ] ];
[request setHTTPBody:postData];
self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
}
else {
NSURL * url;
NSMutableURLRequest * request;
NSString *_urlString = #"http://10.85.28.99/req_light.php";
url = [self smartURLForString:_urlString];
request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
//I got one error and one warring
//Error is "Request for member 'plist' in something not a structure or union"
//Warning is 'NSString' may not resopnd to '+stringWithFormat:value=ForKey'
NSString *post = [ NSString stringWithFormat:#"id=%i,status=0",
[[self.plist objectAtIndex:indexPath.row] valueForKey:#"id"]];
NSData *postData = [ NSData dataWithBytes: [ post UTF8String ] length: [ post length ] ];
[request setHTTPBody:postData];
self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
}
}
So...my question is
<1>How to post two data back (is it right to use "," to separated two return variables ?
<2>How to eliminate the error "Request for member 'plist' in something not a structure or union"
Great Thanks
1) POST values are separated by '&' like GET values in an URL.
2) The 'Request for member'... line tells you that your member does not exist, or at least is not declared in this scope, the warning 'NSString may not respond...' tells you you're trying to invoke a message/method on NSString which should be invoked on another class (NSDictionary would be my guess here).