I try to send title and message to web server. I want to receive response if the request is successful or failure. But I don't from where to start. Can someone help me?
Best regards
It's much prefered to use a ASIHTTPRequest for proper error handling, but a quick and dirty solution could be:
NSString *response = [NSString stringWithContentsOfURL:[NSURL URLWithString:#"http://xxx.yyy"] encoding:NSUTF8StringEncoding error:nil];
BOOL success = response!=nil && ([response rangeOfString:#"success"].location != NSNotFound);
An good library is ASIHTTPRequest.
You can look at apples URL Loading System Programming Guide
Use ASIHTTPRequest it is a wrapper for CFNetowork that lets you easily do what you want.
Related
I'm trying to implement Like via the facebook open-graph-api with the Facebook iOS SDK 3.0.
Everything seems to work except the FbGraphObject and that's because I have no idea how it should look because this clearly does not work.
What I'm trying to do is to like a url posted as an object. A simple Like with via the open-graph.
The error message I get the the code below is:
The action you're trying to publish is invalid because it does not specify any
reference objects. At least one of the following properties must be specified: object.
The code I use is this:
FBGraphObject *objectToLike = [[FBGraphObject alloc]initWithContentsOfURL:[NSURL URLWithString:facebookLike.titleLabel.text]];
FBRequest *requestLike = [[FBRequest alloc]initForPostWithSession:[FBSession activeSession] graphPath:#"me/og.likes" graphObject:objectToLike];
FBRequestConnection *connection = [[FBRequestConnection alloc] init];
[connection addRequest:requestLike
completionHandler:
^(FBRequestConnection *connection, id result, NSError *error) {
if (!error &&
result) {
DLog(#"NothingWentWrong");
}
DLog(#"MajorError: %#", error);
}
];
[connection start];
UPDATE:
Checked some more info and my guess it to use this method:
https://developers.facebook.com/docs/sdk-reference/iossdk/3.0/class/FBGraphObject/#//api/name/graphObject
To somehow create an object. It's the graphObject method that I probably need to do something with. Any help at all would be appreciated.
I've actually manage to create a simple and quite dirty solution of this.
The solution does not seem optimal but it's currently a working solution.
If anybody has used the explorer tool on facebook on this url:
https://developers.facebook.com/tools/explorer/
You know how the URL will look like when facebook is sharing a like. It has to have the URL and an access-token.
So my solution became just to disregard sending anything from the Facebook SDK and just send a post request to the same URL that I've used in the explorer tool.
There seems to be some referencing to it on the facebooks docs if you look closely and deep, but no one explains exactly how to actually make the connection, so this is my solution:
NSString *urlToLikeFor = facebookLike.titleLabel.text;
NSString *theWholeUrl = [NSString stringWithFormat:#"https://graph.facebook.com/me/og.likes?object=%#&access_token=%#", urlToLikeFor, FBSession.activeSession.accessToken];
NSLog(#"TheWholeUrl: %#", theWholeUrl);
NSURL *facebookUrl = [NSURL URLWithString:theWholeUrl];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:facebookUrl];
[req setHTTPMethod:#"POST"];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&err];
NSString *content = [NSString stringWithUTF8String:[responseData bytes]];
NSLog(#"responseData: %#", content);
If you look at the code I just take the url and puts two dynamic strings in the url, one with the object-url and one with the access token. I create a URLRequest and make it a POST request, and the response from facebook gets logged so one actually can see if the like go through or not.
There might be some performance improvements that can be done with the actual requests but I will leave it up to you if you see any slowdowns.
I'm still interested in other solutions but this is the one I will use for now.
We don't currently support Like through our Graph API.
What you can look through is something like this :
https://developers.facebook.com/docs/opengraph/actions/builtin/likes/
I’m not sure what initWithContentsOfURL does, but from the name I guess it tries to actually load content from a given URL(?).
You only have to give the URL as a text parameter – a URL is what represents an Open Graph object. Facebook will do the rest, scraping the page behind that URL and reading it’s OG meta tags, etc.
Maybe just this?
FBRequest *requestLike = [[FBRequest alloc]initForPostWithSession:[FBSession activeSession]
graphPath:#"me/og.likes"
graphObject:[NSURL URLWithString:facebookLike.titleLabel.text]];
I'm working on making a client for my REST service on the iPhone. I'm a little lost as to how I go about making the GET and POST requests. I make the url from a NSString, convert it to an NSURL and create the NSURLRequest based off of the url. After that I'm pretty lost. Also, sometimes I care about the response, other times I don't. For example, when making a request for a new id, I care about the response because it's the id I'll use to upload my file later, but when I upload the file I don't care because the server doesn't send a response.
Does anyone have some (hopefully)simple sample code that they could point me to / share?
What I have so far:
-(NSString *) makeGetRequest:(NSString *)url :(Boolean)careAboutResult
{
NSString *results = nil;
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
NSError *reqError;
NSURLResponse *response = nil;
if(careAboutResult == YES)
{
//get the result
}
return results;
}
In the code I'm testing with, the URL is
http://192.168.0.108:8081/TestUploadService/RestfulUpload.svc/id/test123_DOT_png
and I'm saying I do care about the result.
Any help would be greatly appreciated.
#nick its good you have created a NSURLRequest now you just need to create a connection to send this request and receive response, this request is GET request.
To make POST request you will need to use NSMutableURLRequest and set its method name and body content. Here in documentation you will find how you can do this.
I have an app in the App Store that uses geofences to post updates to our local API. To date, this has been a smashing success. A couple months ago I installed Flurry to get some insight into customer usage and any unhandled exceptions out there. What I started getting back were some errors pertaining to the saved token we use to authenticate the user id.
This token is an MD5 salted hash of the username and password. No issues here, we use it for everything in the app. I store it in the NSUserDefaults and retrieve it before every API call. As we started narrowing down our search for the culprit, it is showing that we are sending a token that doesn't exist anywhere on our servers. When the user trips a geofence, it updates their status automatically, but a very small percent has been failing in the background causing some customer concerns.
Sorry for the long precursor, on to the question. What would cause my value in NSUserDefaults to get loaded to an NSString differently from one time to the next? I have tested the logic, it will update me 3 times in a row when I show up for work, but the 4th, I'll get a token failure error back from the server. There is no rhyme or reason to why it fails. Our server is logging these failed tokens and we can't match them up to anything.
So if anyone has any insight on this matter, I would very much appreciate it. Could it be messing up when I store it to NSString? Could it be some inconsistencies with my POST method? It might even be on our server, I dunno. I'm hoping everyone on SO can lend a hand and help me get some new insight. Thanks in advance.
//Loading the token... done this way for EVERY API call
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *token = [defaults objectForKey:#"token"];
Code taken from my API class
//My POST method for updating our API
NSString *requestData = [NSString stringWithFormat:#"?auth_token=%#", token];
NSData *myRequestData = [NSData dataWithBytes: [requestData UTF8String] length: [requestData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString:[NSString stringWithFormat:#"%#/api/user.json%#", webAddress, requestData]]];
[request setHTTPMethod: #"POST"];
[request setHTTPBody: myRequestData];
NSData *jsonData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil];
NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSDictionary *payloadData = [json JSONValue];
if([[payloadData objectForKey:#"success"] boolValue]) {
// if i get here, successful update
} else {
// update unsuccessful, error message returned... bad token
}
Are you using any 3rd party libraries? "token" is a very common string, I would change it to something else. It's possible some other code is stomping on your token with their token.
I don't want this question to linger out there and waste anyone's time or energy. After some recent testing, I don't believe my issue is with the user defaults or the saved token. There are already answers out there, so I can't delete the question. So I'll just leave a small answer here and close it out.
I ended up moving all the login credentials to the iOS keychain. I salt and hash the email and password each time I need an API token. It creates a little more overhead for each API, but knowing my users' credentials are safe and secure is probably worth it. I still have my issue, but I think I'm getting closer to nailing it down. Thank you to anyone that has looked at my question.
I want to integrate Twitter in my iPhone App for getting some tweets of a particular twitter account. Please suggest me the best idea to do that ?
NOTE:
1) I just want to show the tweets from a particular account. Any short
method will be help full rather than full twitter integration
2) For now I am using RSS to get the tweets but somewhere I've heard
that RSS twitter feeds are very unreliable and they are going to stop
support for RSS soon.
Regards !!
If you don't want to use a full implementation, you just need to perform a query to the statuses of the specific user
For example, to get the last 20 tweet from charliesheen with ASIHTTPRequest
NSURL *url = [NSURL URLWithString:#"http://twitter.com/statuses/user_timeline/charliesheen.xml"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
[request startAsynchronous];
- (void)requestFinished:(ASIHTTPRequest *)request {
// this is called if the request is successful
}
- (void)requestFailed:(ASIHTTPRequest *)request {
// this is called if the request fails
}
If don't want to use xml, just change it to json
http://twitter.com/statuses/user_timeline/charliesheen.json
https://github.com/jaanus/PlainOAuth/tree/27a8631a5e32c36ea40d532c8343fafe7cc5e95c
And download the source project..
This links provide you last five tweets..
Got the answer.
- I added MGTwitterEngine into my project.
Here is the code :[MyViewController's -(void)viewDidLoad]-
MGTwitterEngine *twitterEngine = [[MGTwitterEngine alloc] initWithDelegate:self];
[twitterEngine getUserTimelineFor:username sinceID:0 startingAtPage:0 count:10];
If you guys need some more clarification feel free to ask. I'll try to help you out as much as I can.
Regards!!
I am planning to make an iPhone search app. the user types in the search string. the string will be searched by some search engines like Google, Live, Yahoo ...
I need to get the search result in the XML format. Is there any way to do this. Help needed. Please.
Thanks and regards,
Shibin
A RESTful search request to Google AJAX returns a response in JSON format. JSON is a like a very highly stripped-down version of XML.
Google doesn't make its SOAP interface available any longer, so I don't know if you'll be able to get XML from them, at least through a public interface. Luckily for you, JSON responses are trivial to request and to parse on the iPhone.
You can issue the request with ASIHTTPRequest and parse the JSON-formatted response on an iPhone with json-framework.
For example, to create and submit a search request that is based on the example on the Google AJAX page, you could use ASIHTTPRequest's -requestWithURL and -startSynchronous methods:
NSURL *searchURL = [NSURL URLWithString:#"http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=Paris%20Hilton"];
ASIHTTPRequest *googleRequest = [ASIHTTPRequest requestWithURL:searchURL];
[googleRequest addRequestHeader:#"Referer" value:[self deviceIPAddress]];
[googleRequest startSynchronous];
You would build the NSURL instance based on your search terms, escaping the request parameters.
If I followed Google's example to the letter, I would also add an API key to this URL. Google asks that you use an API key for REST searches. You should sign up for an API key over here and add it to your requests.
You should also specify the referer IP address in the request header, which in this case would be the local IP address of the iPhone, e.g.:
- (NSString *) deviceIPAddress {
char iphoneIP[255];
strcpy(iphoneIP,"127.0.0.1"); // if everything fails
NSHost *myHost = [NSHost currentHost];
if (myHost) {
NSString *address = [myHost address];
if (address)
strcpy(iphoneIP, [address cStringUsingEncoding:NSUTF8StringEncoding]);
}
return [NSString stringWithFormat:#"%s",iphoneIP];
}
There are also asynchronous request methods which are detailed in the ASIHTTPRequest documentation. You would use those to keep the iPhone UI from getting tied up while the search request is made.
In any case, once you have Google's JSON-formatted response in hand, you can use the json-framework SBJSON parser object to parse the response into an NSDictionary object:
NSError *requestError = [googleRequest error];
if (!requestError) {
SBJSON *jsonParser = [[SBJSON alloc] init];
NSString *googleResponse = [googleRequest responseString];
NSDictionary *searchResults = [jsonParser objectWithString:googleResponse error:nil];
[jsonParser release];
// do stuff with searchResults...
}
There are different web service API's available. I would recommend that you use those.
Google Search API: http://code.google.com/intl/sv-SE/apis/ajaxsearch/web.html
Google JS API's often return JSON. But that's easy to work with too. You should easily be able to transform the JSON to XML if needed.