I am getting EXC_BAD_ACCESS on the Line:
[asiUsernameRequest startAsynchronous];
in this code. Spent hours trying to figure it out, but no solution. Any idea?
NSString *usernameValue = (NSString*)usernameField.text;
NSLog(#"username selected: %#", usernameValue);
NSURL *url = [NSURL URLWithString:#"http://www.mywebsite.com/api/usernameCheck"];
//ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
asiUsernameRequest = [[[ASIFormDataRequest alloc] initWithURL:url] retain];
[asiUsernameRequest setPostValue:usernameValue forKey:#"username"];
NSArray *objects = [NSArray arrayWithObjects:#"usernameCheck", nil];
NSArray *keys = [NSArray arrayWithObjects:#"action", nil];
asiUsernameRequest.userInfo = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
[asiUsernameRequest setDelegate:self];
[asiUsernameRequest startAsynchronous];
Try retaining the usernameField's text:
NSString * usernameValue = [[usernameField.text] retain];
Related
I'm trying to integrate LinkedIn in my iOS application, where I need to Authenticate, then fetch profile details and post to LinkedIn from my app. I do all these things quite successfully using this sample project LinkedIn OAuth Sample Client as reference, I did some modifications and everything is working quite well. And I use the details from
LinnkedIn API as well to implement this.
Next, I need to send invitation to connect in LinkedIn from the same app. I tried using Invitataion API .
Here is my code snippet:
-(void)sendInvitationToconnectTo:(NSString *)emailAddress withMessage:(NSString *)text
{
NSURL *url = [NSURL URLWithString:#"http://api.linkedin.com/v1/people/~/mailbox"];
OAMutableURLRequest *request = [[OAMutableURLRequest alloc] initWithURL:url
consumer:oAuthLoginView.consumer
token:oAuthLoginView.accessToken
callback:nil
signatureProvider:[[OAHMAC_SHA1SignatureProvider alloc] init]];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSDictionary *temp=[[NSDictionary alloc]initWithObjectsAndKeys:#"/people/email=userName#gmail.com",#"_path",#"userName1",#"first-name",#"userName2",#"last-name", nil];
NSDictionary *temp2=[[NSDictionary alloc] initWithObjectsAndKeys:temp,#"person",nil];
NSArray *arr2=[[NSArray alloc]initWithObjects:temp2, nil];
NSDictionary *value=[[NSDictionary alloc]initWithObjectsAndKeys:arr2,#"values", nil];
NSDictionary *dict3=[[NSDictionary alloc]initWithObjectsAndKeys:#"friend",#"connect-type",nil];
NSDictionary *dict4=[[NSDictionary alloc] initWithObjectsAndKeys:dict3,#"invitation-request", nil];
NSDictionary *dict=[[NSDictionary alloc]initWithObjectsAndKeys:dict4,#"item-content",#"Say yes!",#"body",#"Invitation to connect.",#"subject",value,#"recipients", nil];
NSString *updateString = [dict JSONString];
NSLog(#"updateString : %#",updateString);
[request setHTTPBodyWithString:updateString];
[request setHTTPMethod:#"POST"];
OADataFetcher *fetcher = [[OADataFetcher alloc] init];
[fetcher fetchDataWithRequest:request
delegate:self
didFinishSelector:#selector(sendRequestApiCallResult:didFinish:)
didFailSelector:#selector(sendRequestApiCallResult:didFail:)];
[request release];
}
- (void)sendRequestApiCallResult:(OAServiceTicket *)ticket didFinish:(NSData *)data
{
NSLog(#"invitation sent");
[self networkApiCall];
}
- (void)sendRequestApiCallResult:(OAServiceTicket *)ticket didFail:(NSData *)error
{
NSLog(#"%#",[error description]);
}
And my json string looks like this:
{"body":"Say yes!","subject":"Invitation to
connect.","recipients":{"values":[{"person":{"first-name":"userName1","last-name":"userName2","_path":"/people/email=userName#gmail.com"}}]},"item-content":{"invitation-request":{"connect-type":"friend"}}}
While sending the invitation I don't get any errors and when I debug, the sendRequestApiCallResult:(OAServiceTicket *)ticket didFinish:(NSData *)data method gets called showing invitation sent text.
But ths issue is the target LinkedIn user didn't get any request!
Can anyone help me regarding this? Is there anything I'm doing wrong in my code?
NB I went through both the below mentioned links to get a solution, tried the solutions , but in vain.
1.Invitation API - Stumped by 401 (iOS and OAuthConsumer) - SOLVED
2.linkedin connect API gives error 401 - iphone
and the NSURLResponse statuscode I get is 401 !
EDIT:: Solved it myself. See my answer below.
Glad to inform all that after long 4 days of continuos research, I got this problem solved!
I got the solution from this Linkedin thread
You just need to make a few changes in the code:
NSURL *url = [NSURL URLWithString:#"http://api.linkedin.com/v1/people/~/mailbox"];
OAMutableURLRequest *request =
[[OAMutableURLRequest alloc] initWithURL:url
consumer:oAuthLoginView.consumer
token:oAuthLoginView.accessToken
callback:nil
signatureProvider:nil];
[request setHTTPMethod:#"POST"];
NSString *messageToPerson = #"/people/email=target#gmail.com";
NSDictionary *person = [[NSDictionary alloc] initWithObjectsAndKeys:[[[NSDictionary alloc] initWithObjectsAndKeys:messageToPerson,#"_path",#"TargetFirstName",#"first-name",#"TargetSecondName",#"last-name",nil] autorelease], #"person",nil];
NSArray *valueArray = [[NSArray alloc] initWithObjects:person,nil];
NSDictionary *values = [[NSDictionary alloc] initWithObjectsAndKeys:valueArray,#"values", nil];
NSDictionary *ir = [[NSDictionary alloc] initWithObjectsAndKeys:[[[NSDictionary alloc] initWithObjectsAndKeys:#"friend",#"connect-type",nil] autorelease], #"invitation-request",nil];
NSDictionary *ic = [[NSDictionary alloc] initWithObjectsAndKeys:ir,#"item-content", nil];
NSDictionary *update = [[NSDictionary alloc] initWithObjectsAndKeys:values,#"recipients",#"Invitation",#"subject",#"ConnectWithMe",#"body", ir, #"item-content", nil];
[request setValue:#"json" forHTTPHeaderField:#"x-li-format"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSLog(#"%#",[update description]);
NSString *updateString = [update JSONString];
[request prepare];
[request setHTTPBodyWithString:updateString];
OADataFetcher *fetcher = [[OADataFetcher alloc] init];
[fetcher fetchDataWithRequest:request delegate:self
didFinishSelector:#selector(postUpdateApiCallResult:didFinish:)
didFailSelector:#selector(postUpdateApiCallResult:didFail:) withId:1];
[request release];
and
in oAdata OADataFetcher.m
- (void)fetchDataWithRequest:(OAMutableURLRequest *)aRequest delegate:(id)aDelegate didFinishSelector:(SEL)finishSelector didFailSelector:(SEL)failSelector withId:(int)idtm
{
[request release];
request = [aRequest retain];
delegate = aDelegate;
didFinishSelector = finishSelector;
didFailSelector = failSelector;
//note this change
if (idtm!=1) {
[request prepare];
}
connection = [[NSURLConnection alloc] initWithRequest:aRequest delegate:self];
}
Try this. Will work for sure. Hope this will help future visitors.
Regards
I am passing some parameters to wcf service to get the data, every thing running fine but i am not getting the data. i want to check how the parameters are calling the service and debug it. can any one let me know how to check it.
please find my code below for your reference.
NSArray *propertyNames = [NSArray arrayWithObjects:#"studentID", nil];
NSArray *propertyValues = [NSArray arrayWithObjects:#"E6A83233-7D7F-49AF-B54E-375BBF3E3E59", nil];
NSDictionary *properties = [NSDictionary dictionaryWithObjects:propertyValues forKeys:propertyNames];
// NSMutableDictionary* personObject = [NSMutableDictionary dictionary];
// [personObject setObject:properties forKey:#"person"];
NSMutableArray * arr;
//[arr addObject: personObject];
arr=[[NSMutableArray alloc]initWithObjects:properties, nil];
NSLog(#"%#",arr);
// NSString *jsonString = [personObject JSONRepresentation];
//NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError * error;
NSData *jsonData2 = [NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:&error];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://parentportal.technologyorg.com/parentportal.svc/GetSchoolEvents"]];
NSString *jsonString = [[NSString alloc] initWithData:jsonData2 encoding:NSUTF8StringEncoding];
[request setValue:jsonString forHTTPHeaderField:#"json"];
[request setHTTPMethod:#"Post"];
[request setHTTPBody:jsonData2];
NSLog(#"JSON String: %#",jsonString);
NSError *errorReturned = nil;
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&errorReturned];
if (errorReturned) {
//...handle the error
NSLog(#"error");
}
else {
NSString *retVal = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//...do something with the returned value
NSLog(#"RETVAL%#",retVal);
}
let me know if any thing went wrong
I am using OAuth-Sample-Client code to send invitation from email address via Linked Invitation API.
I have created the same body as described in developer site,but right now I am getting error of 401,I have searched a lot of on it but didn't get any solution which get me out of it from any site or forum.
My response is as below.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<error>
<status>401</status>
<timestamp>1351159386437</timestamp>
<request-id>YX4NRU3S7J</request-id>
<error-code>0</error-code>
<message>[unauthorized]. OAU:ron8e8nko3te|e0a96317-dfdc-44fb-b427-5655e02f97ed|*01|*01:1351159294:dRCDN6b3K9F/mwWAaByKZQPgeVw=</message>
</error>
Here my json string would be like this:
{"body":"Say yes!","subject":"Invitation to
connect.","recipients":{"values":[{"person":{"first-name":"test","last-name":"test","_path":"/people/email=test#test.com"}}]},"item-content":{"invitation-request":{"connect-type":"friend"}}}
I have used the code as below to send Invitation.
- (IBAction)postButton_TouchUp:(UIButton *)sender
{
[statusTextView resignFirstResponder];
NSURL *url = [NSURL URLWithString:#"http://api.linkedin.com/v1/people/~/mailbox"];
OAMutableURLRequest *request =
[[OAMutableURLRequest alloc] initWithURL:url
consumer:oAuthLoginView.consumer
token:oAuthLoginView.accessToken
callback:nil
signatureProvider:[[OAHMAC_SHA1SignatureProvider alloc] init]];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSDictionary *temp=[[NSDictionary alloc]initWithObjectsAndKeys:#"/people/email=test#test.com",#"_path",#"test",#"first-name",#"test",#"last-name", nil];
NSDictionary *temp2=[[NSDictionary alloc] initWithObjectsAndKeys:temp,#"person",nil];
NSArray *arr2=[[NSArray alloc]initWithObjects:temp2, nil];
NSDictionary *value=[[NSDictionary alloc]initWithObjectsAndKeys:arr2,#"values", nil];
NSDictionary *dict3=[[NSDictionary alloc]initWithObjectsAndKeys:#"friend",#"connect-type",nil];
NSDictionary *dict4=[[NSDictionary alloc] initWithObjectsAndKeys:dict3,#"invitation-request", nil];
NSDictionary *dict=[[NSDictionary alloc]initWithObjectsAndKeys:dict4,#"item-content",#"Say yes!",#"body",#"Invitation to connect.",#"subject",value,#"recipients", nil];
NSLog(#"%#",[dict description]);
NSString *updateString = [dict JSONString];
[request setHTTPBodyWithString:updateString];
[request setHTTPMethod:#"POST"];
OADataFetcher *fetcher = [[OADataFetcher alloc] init];
[fetcher fetchDataWithRequest:request
delegate:self
didFinishSelector:#selector(postUpdateApiCallResult:didFinish:)
didFailSelector:#selector(postUpdateApiCallResult:didFail:)];
[request release];
}
I got stuck at this point,Please get me out of this.
-Thanks in advance
call prepare method of OADataFetcher manually. Just put it before setting the body of the request.
[request prepare];
[request setHTTPBodyWithString:updateString];
This is working for me.
Also remove the prepare method from the OADataFetcher when you are working with Invitation API.
Apple's code works! Just one more thing, dont forget any header. I was still getting the same message, turns out I forgot to add x-li-format and Content-type headers.
I got the solution from this Linkedin thread
You just need to make a few changes in the code:
NSURL *url = [NSURL URLWithString:#"http://api.linkedin.com/v1/people/~/mailbox"];
OAMutableURLRequest *request =
[[OAMutableURLRequest alloc] initWithURL:url
consumer:oAuthLoginView.consumer
token:oAuthLoginView.accessToken
callback:nil
signatureProvider:nil];
[request setHTTPMethod:#"POST"];
NSString *messageToPerson = #"/people/email=target#gmail.com";
NSDictionary *person = [[NSDictionary alloc] initWithObjectsAndKeys:[[[NSDictionary alloc] initWithObjectsAndKeys:messageToPerson,#"_path",#"TargetFirstName",#"first-name",#"TargetSecondName",#"last-name",nil] autorelease], #"person",nil];
NSArray *valueArray = [[NSArray alloc] initWithObjects:person,nil];
NSDictionary *values = [[NSDictionary alloc] initWithObjectsAndKeys:valueArray,#"values", nil];
NSDictionary *ir = [[NSDictionary alloc] initWithObjectsAndKeys:[[[NSDictionary alloc] initWithObjectsAndKeys:#"friend",#"connect-type",nil] autorelease], #"invitation-request",nil];
NSDictionary *ic = [[NSDictionary alloc] initWithObjectsAndKeys:ir,#"item-content", nil];
NSDictionary *update = [[NSDictionary alloc] initWithObjectsAndKeys:values,#"recipients",#"Invitation",#"subject",#"ConnectWithMe",#"body", ir, #"item-content", nil];
[request setValue:#"json" forHTTPHeaderField:#"x-li-format"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSLog(#"%#",[update description]);
NSString *updateString = [update JSONString];
[request prepare];
[request setHTTPBodyWithString:updateString];
OADataFetcher *fetcher = [[OADataFetcher alloc] init];
[fetcher fetchDataWithRequest:request delegate:self
didFinishSelector:#selector(postUpdateApiCallResult:didFinish:)
didFailSelector:#selector(postUpdateApiCallResult:didFail:) withId:1];
[request release];
and in oAdata OADataFetcher.m
- (void)fetchDataWithRequest:(OAMutableURLRequest *)aRequest delegate:(id)aDelegate didFinishSelector:(SEL)finishSelector didFailSelector:(SEL)failSelector withId:(int)idtm
{
[request release];
request = [aRequest retain];
delegate = aDelegate;
didFinishSelector = finishSelector;
didFailSelector = failSelector;
//note this change
if (idtm!=1) {
[request prepare];
}
connection = [[NSURLConnection alloc] initWithRequest:aRequest delegate:self];
}
Try this. Will work for sure. Hope this will help future visitors.
Regards
I'm new in iPhone and I'm trying to convert NSMutable array to json string then send this string to php file using request, and then print it again using respond to NSLog to ensure that it has been send successfully. So I wrote the following code in viewDidLoad
NSString *phpUrl = #"http://dt-works.com/eman/bookMarks.php";
NSMutableArray *arrayKey = [[NSMutableArray alloc] initWithObjects:#"one", #"two", #"three", nil];
NSMutableArray *arrayValue1 = [[NSMutableArray alloc] initWithObjects:#"1", #"2", #"3", nil];
NSMutableArray *arrayValue2 = [[NSMutableArray alloc] initWithObjects:#"11", #"22", #"33", nil];
NSDictionary *theReqDictionary1 = [NSDictionary dictionaryWithObjects:arrayValue1 forKeys:arrayKey];
NSDictionary *theReqDictionary2 = [NSDictionary dictionaryWithObjects:arrayValue2 forKeys:arrayKey];
NSMutableArray *myArray = [NSMutableArray arrayWithObjects:theReqDictionary1,theReqDictionary2, nil];
NSString *jsonString = [myArray JSONRepresentation];
NSLog(#"%#", jsonString);
NSDictionary *questions = nil;
NSURL *link = [NSURL URLWithString:[phpUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:link];
[request setPostValue:jsonString forKey:#"jsonString"];
[request setTimeOutSeconds:120];
[request setDelegate:self];
NSError *error = [request2 error];
[request2 startSynchronous];
if (!error) {
NSData *response = [request responseData];
NSString *json = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
questions = [json objectFromJSONString];
NSLog(#"Data: %#", questions);
}
and the code in bookMarks.php is:
$handle = fopen('php://input','r');
$jsonInput = $_POST['jsonString'];
print_r($jsonInput);
but it gives me:
[{"one":"1","two":"2","three":"3"},{"one":"11","two":"22","three":"33"}]
Data: (null)
and I want Data to be as: [{"one":"1","two":"2","three":"3"},{"one":"11","two":"22","three":"33"}]
how to do this??
Try this, instead of posting the JSON string with a key, you need to post it as Data to your script to be read in. Currently in your script you aren't even using $handle for anything...
NSURL *link = [NSURL URLWithString:[phpUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:link];
[request appendPostData:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
[request setTimeOutSeconds:120];
[request setDelegate:self];
And your php code..
$handle = fopen('php://input','r');
$jsonInput = fgets($handle);
$decoded = json_decode($jsonInput,true);
print_r($decoded);
I am attempting to POST some simple JSON to a RESTful service. I want to form a json string that takes the following form:
{username:"someuser",password:"somepassword"}
My POST keeps failing at the server complaining that POSTed values do not exist. However the same service works fine if I create a JS test implementation. So I'm pretty sure its my SBJson client implementation that is the problem.
NSDictionary *userDict = [[NSDictionary alloc] initWithObjectsAndKeys:
userName,#"username",
password, #"password",
nil];
SBJsonWriter *writer = [[SBJsonWriter alloc]init];
NSData *jsonData = [writer dataWithObject:userDict];
jsonData appears to have size but it attempt to serialize it with SBJson its fails and I get nil.
NSString *test = [writer stringWithObject:jsonData]; // returns nil
I am trying to post the above in a NSMutableURLRequest. Here's my implementation if it helps give context:
-(void)registerUserName:(NSString *)userName andPassword:(NSString *)password{
responseData = nil;
responseData = [NSMutableData data];
NSDictionary *userDict = [[NSDictionary alloc] initWithObjectsAndKeys:
userName,#"username",
password, #"password",
nil];
SBJsonWriter *writer = [[SBJsonWriter alloc]init];
NSData *jsonData = [writer dataWithObject:userDict];
NSString *test = [writer stringWithObject:jsonData]; //always nil
NSURL *url = [[NSURL alloc] initWithString:#"http://localhost/~user/app_web/index.php/user/create"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:#"POST"];
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request addValue:#"form-data" forHTTPHeaderField:#"Content-Disposition"];
[request setHTTPBody:jsonData];
[[UIApplication sharedApplication]setNetworkActivityIndicatorVisible:YES ];
currentRequestType = REGISTER_USER;
NSURLConnection *connection =[[NSURLConnection alloc]initWithRequest:request delegate:self];
Thanks!
update
Using the suggestions below I am now doing this:
NSDictionary *userDict = [[NSDictionary alloc] initWithObjectsAndKeys:
userName,#"username",
password, #"password",
nil];
NSString *jsonString = [userDict JSONRepresentation];
NSData *jsonData = [jsonString dataUsingEncoding];
[request setHTTPBody:jsonData];
[[UIApplication sharedApplication]setNetworkActivityIndicatorVisible:YES ];
currentRequestType = REGISTER_USER;
NSURLConnection *connection =[[NSURLConnection alloc]initWithRequest:request delegate:self];
Unfortunately my posted values are still not found at the server. I think something must be wrong with my NSMutableURLRequest..
I am using CodeIgniter on the backend. The action looks like this:
public function create(){
if($this->input->post('username') && $this->input->post('password')){
$username = $this->input->post('username');
$password = $this->input->post('password');
$this->load->model('User_model','users');
$status = $this->users->add_user($username,$password);
if($status){
echo json_encode(array('success'=>true));
} else{
echo json_encode(array('success'=>false));
}
}
echo json_encode(array('success'=>false)); // when posting I arrive here
}
To serialize the dictionary userDict call the following method.
NSString* jsonString = [userDict JSONRepresentation];
If you want the NSData representation you can use the following method
NSData* jsonData = [jsonString dataUsingEncoding:NSUTF8Encoding];
try this:
NSDictionary *userDict = [[NSDictionary alloc] initWithObjectsAndKeys:
userName,#"username",
password, #"password",
nil];
SBJsonWriter *writer = [[SBJsonWriter alloc]init];
NSString *test = [writer stringWithObject:userDict];
don't forget to release them