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).
Related
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];
I have searched a lot on google as well as on stackoverflow but did not get any satisfactory solution which works for me.
I have to upload an image on some particular url which is ending with extension .ashx.
I have seen how to upload on php server but here i am not getting any clue.
Please help me by providing some sample code.
As per my understanding aspx is the page and the .ashx is the code file which response back the output, in string format and .ashx file is a web handler. A web handler file works just like an aspx file....
So we consider.ashx same as .aspx then this code should work for you(which is running for me for .aspx page). This is making request to .net server.
iOS
UIImage *img = [UIImage imageNamed:#"test.png"];
NSData *imageData = UIImageJPEGRepresentation ( img , 90 );
NSString *urlString =#"www.xyz.com/ImageUpload.aspx?filename=test";
NSLog(#"IMAGE_UPLOAD_URL -------------> %#",urlString);
NSMutableURLRequest *request = [[[ NSMutableURLRequest alloc ] init ] autorelease ];
[request setURL :[ NSURL URLWithString :urlString]];
[request setHTTPMethod : #"POST" ];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [ NSString stringWithFormat : #"multipart/form-data; boundary=%#" ,boundary];
[request addValue :contentType forHTTPHeaderField : #"Content-Type" ];
/* body of the post */
NSMutableData *body = [ NSMutableData data ];
[body appendData :[ NSData dataWithData :imageData]];
[request setHTTPBody :body];
NSData *returnData = [ NSURLConnection sendSynchronousRequest :request returningResponse : nil error : nil ];
NSString *returnString = [[ NSString alloc ] initWithData :returnData encoding : NSUTF8StringEncoding ];
InfoLog(#"_______ IMAGE_UPLOAD response -------------> .%#.",returnString);
.NET
Retrieving image like this for .aspx page
if (Request.QueryString["filename"] != null)
{
string filename = Request.QueryString["filename"].ToString();
string saveFilePath = ConfigurationManager.AppSettings["CPSBImageFolder"].ToString();
//string saveFilePath = Server.MapPath("~/images");
saveFilePath = saveFilePath + filename;
Stream objStream = Request.InputStream;
StreamReader objStreamReader = new StreamReader(objStream);
Image image = Image.FromStream(objStreamReader.BaseStream, true);
ImageCodecInfo[] info = ImageCodecInfo.GetImageEncoders();
EncoderParameters param = new EncoderParameters(1);
param.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
image.Save(saveFilePath, info[1], param);
Response.Write("true");
}
Not sure but hope this give you a clue.
Verify that the variable(NSData) you are using to upload image is not null & your dot net server is receiving request.
I am sending some data from my application to server. my data consist of different fields as my code shown below
-(void)createXML
{
xmlStr = #"<?xml version='1.0'?>\n<jand_req>\n<inquiryList>\n<productArr>\n";
NSString *nameStr=[NSString stringWithFormat:#"<name>%#</name>\n",name.text];
xmlStr=[xmlStr stringByAppendingString:nameStr];
NSString *compNameStr=[NSString stringWithFormat:#"<comp_name>%#</comp_name>\n",compName.text];
xmlStr=[xmlStr stringByAppendingString:compNameStr];
NSString *cityStr=[NSString stringWithFormat:#"<city>%#</city>\n",city.text];
xmlStr=[xmlStr stringByAppendingString:cityStr];
NSString *countryStr=[NSString stringWithFormat:#"<country>%#</country>\n",[nameToCode objectForKey:country.text]];
xmlStr=[xmlStr stringByAppendingString:countryStr];
NSString *commentsStr=[NSString stringWithFormat:#"<comment>%#</comment>\n",commentsBox.text];
xmlStr=[xmlStr stringByAppendingString:commentsStr];
xmlStr=[xmlStr stringByAppendingString:#"</userDetail>\n</inquiryList>\n</jand_req>"];
}
After this i send the above data to server as my code shown below
- (void)submitForm
{
[self createXML];
NSLog(#"myaccesscode%#",[fn getValFromSettings:#"accessCode"]);
NSString *serviceUrlStr=[NSString stringWithFormat:#"%#/%#/API_sendmail.php?access_code=%#",domainName,apiFolderPath,[fn getValFromSettings:#"accessCode"]];
NSLog(#"%#",serviceUrlStr);
NSURL * serviceUrl = [NSURL URLWithString:[serviceUrlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest * serviceRequest = [NSMutableURLRequest requestWithURL:serviceUrl cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:100];
[serviceRequest setValue:#"text/xml" forHTTPHeaderField:#"Content-type"];
[serviceRequest setHTTPMethod:#"POST"];
[serviceRequest setHTTPBody:[xmlStr dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *conn=[[[NSURLConnection alloc] initWithRequest:serviceRequest delegate:self startImmediately:YES] autorelease];
}
All the above code works fine for me but now i want to include an another feature in this code Which consist of sender E-mail address but this sender E-mail must be fetch from device same as when we use MFMailComposeViewController in application then automatically it gets sender E-mail Address from Device.Any help will be appriated thanks.
#import <AddressBook/AddressBook.h>
NSString *emailAddr = #"";
ABPerson *aPerson = [[ABAddressBook sharedAddressBook] me];
ABMultiValue *emails = [aPerson valueForProperty:kABEmailProperty];
if([emails count] > 0)
emailAddr = [emails valueAtIndex:0];
don't forget to add AddressBook.framework.
Now, the emailAddr contains the senders email which you can append to your xml string or wherever you want it to!
-(void)createXML
{
// Your code
NSString *emailStr=[NSString stringWithFormat:#"<email>%#</email>\n",emailAddr];
xmlStr=[xmlStr stringByAppendingString:emailStr];
}
happy coding!
How to get a new access token in Google Oauth 2.0?
I tried this:
NSString * urlString1 = [NSString stringWithFormat:#"https://accounts.google.com/o/oauth2/token?client_id=my_client_id&client_secret=my_client_secret&refresh_token=%#&grant_type=refresh_token",auth.refreshToken];
NSURL * url = [NSURL URLWithString:urlString1];
NSMutableURLRequest * request = [[NSMutableURLRequest alloc] initWithURL:url];
[request addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:#"POST"];
NSURLConnection * connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
[connection start];
But result is: Method Not Allowed (Error 405)
Maybe there is another way to get new access token?
Please help!
Thanks!
HTTP 405 means that you are trying to use a verb that is not allowed by the resource. For example using a POST on a read-only GET resource or PUT on a write resource that only accepts POSTs.
See abraham's answer : Google with oauth 2
please use following code to get access token in Google Plus
First Replase you - (NSString *)description method in GTMOAuth2Authentication.h file and you will surely get G+ Acccess token
- (NSString *)description
{
NSArray *props = [NSArray arrayWithObjects:#"accessToken",nil];//[NSArray arrayWithObjects:#"accessToken", #"refreshToken",#"code", #"assertion", #"expirationDate", #"errorString",nil];
NSMutableString *valuesStr = [NSMutableString string];
NSString *separator = #"";
for (NSString *prop in props) {
id result = [self valueForKey:prop];
if (result)
{
[valuesStr appendFormat:#"%#",result];
separator = #", ";
}
}
return [NSString stringWithFormat:#"%#",valuesStr];
}
in .h file
#class GPPSignInButton;
#interface GPlusView : UIViewController <GPPSignInDelegate>
{
IBOutlet GPPSignInButton *signInButton;
}
#property (retain, nonatomic) IBOutlet GPPSignInButton *signInButton;
in .m file
signInButton_.shouldFetchGoogleUserEmail = TRUE;
signInButton_.delegate = self;
signInButton_.clientID = [SamacharAppDelegate clientID];
signInButton_.scope = [NSArray arrayWithObjects:
#"https://www.googleapis.com/auth/plus.me",
nil];
-(void)finishedWithAuth:(GTMOAuth2Authentication *)auth error:(NSError *)error
{
if (error) {
NSLog(#"Error = %#",error.localizedDescription);
return;
}
NSLog("Auth Data = %#",auth);
/* Auth Data = {accessToken="ya29.AHES6ZQYLmSBc9n4pLj9U8OQrFoTDZnGLH8okPkxbda7B0Q", refreshToken="1/puItTB-sqHupfp9qPCKcb6_gWUjgcxwzc9TKJvUwMEI", expirationDate="2012-11-24 13:30:55 +0000"} */
}
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'