How do I create a post for Disqus from iOS? - ios

I'm developing an application for a client. This app enables user to read and post comment. Our client website have already used Discus. Now that we can retrieve the comment and display it natively. But we find no way to create a post and send it to Disqus. Does anyone have some experiences with Disqus on iOS ?
Any idea will be much appreciated.
Edit : our client website has an authentication system already and thus we also integrate that system to our app. Every time user post a comment in the app, we'll use his/her authentication information. We don't want user to authenticate again.

Here is a great solution which helps easily integrate Disqus into iOS apps https://github.com/moqod/disqus-ios. Works like a charm out of the box.
Not only you can make posts, but also authorize thru social networks and respond to comments.

You have the API set up on your server, correct? Then post a request to your server, pass it whatever API keys and credentials you need, and have the server make a post to the Disqus API on behalf of the client. Basically, build your own iOS API for interfacing with the Disqus API through your server.
Even better though would be to directly interact with the Disqus server by making requests using NSURLRequest/Connection. For more information on Disqus requests look here. That would make your app faster and be less error prone, unless you are doing some critical activity on your server, other than just posting and displaying comments.

#RahuGupta: Sorry if it's too late for a response. I posted comment using SSO, I don't know about posting as guest. But it should be easier.
In my case I post a comment using third party authentication server which means we authenticate users by ourselves. The technique called SSO. You may want to read the documentation about SSO on Disqus.
In case you need code snippet in objective-c :
NSMutableDictionary *dico = [[NSMutableDictionary alloc] init];
[dico setValue:[NSString stringWithFormat:#"uniqueId_%#",comment.authorID] forKey:#"id"];
[dico setValue:comment.authorName forKey:#"username"];
[dico setValue:comment.authorEmail forKey:#"email"];
NSString *message = [dico JSONRepresentation];
NSString *message64Based = [DataPost base64String:message];
NSTimeInterval timeStamp = [[NSDate date] timeIntervalSince1970];
NSString *secret = DISQUS_API_SECRET;
NSString *api_key = DISQUS_API_PUBLIC;
//comment.threadID will makes the app crashed, because when comment is not fully loaded, it's nil
NSString *threadID = [NSString stringWithFormat:#"%#",comment.threadID];
NSString *commentMessage = [[comment.rawMessage stringByReplacingOccurrencesOfString:#"=" withString:#"%3D"] stringByReplacingOccurrencesOfString:#" " withString:#"+"];
NSString *host = #"http://example.com";
NSString *referrer = #"example.com";
NSString *hmac = [self hashedValue:secret andData:[NSString stringWithFormat:#"%# %.0lf",message64Based, timeStamp]];
NSString *remote_auth_s3 = [[[NSString stringWithFormat:#"%# %# %.0lf", message64Based, hmac, timeStamp] stringByReplacingOccurrencesOfString:#"=" withString:#"%3D"] stringByReplacingOccurrencesOfString:#" " withString:#"+"];
NSMutableURLRequest *uploadRequest = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://disqus.com/api/3.0/posts/create.json"] cachePolicy: NSURLRequestReloadIgnoringLocalCacheData timeoutInterval: 60.0f];
NSMutableData *postData = (NSMutableData *)[[NSString stringWithFormat:#"_format=json&thread=%#&message=%#&remote_auth=%#&api_key=%#&strict=1", threadID , commentMessage, remote_auth_s3 , api_key] dataUsingEncoding:NSUTF8StringEncoding];
[uploadRequest setHTTPMethod:#"POST"];
[uploadRequest setHTTPBody: postData];
[uploadRequest setValue:[NSString stringWithFormat:#"%d", [postData length]] forHTTPHeaderField:#"Content-Length"];
[uploadRequest setValue:referrer forHTTPHeaderField:#"referrer"];
[uploadRequest setValue:host forHTTPHeaderField:#"host"];
[uploadRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSHTTPURLResponse *response=nil;
NSError *error = nil;
[NSURLConnection sendSynchronousRequest:uploadRequest returningResponse:&response error:&error];

Related

Fetching an access token for youtube api iOS "Error" : "invalid_request"

I'm trying to get an access token for a youtube app for iOS. Here's the relevant code I have been using from my viewDidLoad method:
mAuth = [[GTMOAuth2Authentication alloc]init];
[mAuth setClientID:#"<MY CLIENT ID>"];
[mAuth setClientSecret:#"<MY CLIENT SECRET>"];
[mAuth setRedirectURI:#"urn:ietf:wg:oauth:2.0:oob"];
[mAuth setScope:#"https://gdata.youtube.com"];
[self.web loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"https://accounts.google.com/o/oauth2/auth?client_id=%#&redirect_uri=%#&scope=%#&response_type=code&access_type=offline", mAuth.clientID, mAuth.redirectURI, mAuth.scope]]]];
After this is called, the user has to grant access to their account, then I retrieve the auth code from the resulting page in the following code:
NSString *string = [self.web stringByEvaluatingJavaScriptFromString:#"document.title"];
if([string rangeOfString:#"Success"].location != NSNotFound){
NSLog(#"This is the code page");
NSString *importantCode = [[string componentsSeparatedByString:#"="] objectAtIndex:1];
NSLog(#"%#", importantCode);
if([self.defaults objectForKey:#"super important code"] == nil){
[self.defaults setObject:importantCode forKey:#"super important code"];
[self.defaults synchronize];
NSString *post = [NSString stringWithFormat:#"code=%#&client_id=%#&client_secret=%#&redirect_uri=%#&grant_type=code", [self.defaults objectForKey:#"super important code"], mAuth.clientID, mAuth.clientSecret, mAuth.redirectURI];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"https://accounts.google.com/o/oauth2/token"]]];
[request setHTTPMethod:#"POST"]; [request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
[self.web loadRequest:request];
}
[timer invalidate];
}
After that, I should be given the access token in response to my POST request, but instead I get a page that simply says:
{
"error" : "invalid_request"
}
Does anyone (see where I went wrong)/(know how to retrieve the access token)?
I’d be interested in knowing what the HTTP status code is... I suspect ”invalid_request” means 400, which almost always means there’s some irritating stupid little error in the way you composed your authent URI. I don’t know enough iOS/ObcJ to tell if you’ve properly URLescaped any funny characters in any of the parameter values, but it’s worth checking. Or a typo in one of the values, or an extra newline creeping in or something?
It was as simple as this, I had set the grant_type parameter to 'code' when it should have been 'authorisation_code' if you are reading this and you are using the youtube api, don't make the same mistake. If you're reading this and you're sending a POST request in general, this error "invalid_request" means that either you skipped one of the parameters you should have added, or you added it incorrectly.

In App Purchase Autorenew Receipt Format Problems

I have an auto-renewable in-app purchase. When the user signs up for the first time, the app receives a receipt in the form of NSDATA. I encode that into a string:
[NSString stringWithUTF8String:[receiptData bytes]]];
Then I post it to my server as a blob.
Then when the user signs into the app, I get the receipt from my server, change it into NSDATA:
[receipt dataUsingEncoding:NSUTF8StringEncoding]
then I run a method on it to verify that the receipt is valid. From my reading I have gathered that responses will be a newer receipt, or a status code of some sort saying its valid or not.
NSString *jsonObjectString = [self encodeBase64:(uint8_t *)receipt.bytes
length:receipt.length];
NSString *itunescombo = #"xxxxxxxxxxxxxxxxxxxxxx";
// Create the POST request payload.
NSString *payload = [NSString stringWithFormat:#"{\"receipt-data\" : \"%#\", \"password\" : \"%#\"}",
jsonObjectString, itunescombo];
NSData *payloadData = [payload dataUsingEncoding:NSUTF8StringEncoding];
NSString *serverURL = ITMS_SANDBOX_VERIFY_RECEIPT_URL;
// Create the POST request to the server.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:serverURL]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:payloadData];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[conn start];
Then as a response, I keep getting either:
{"status":21002, "exception":"java.lang.IllegalArgumentException"}
or just
{"status":21002}
Can someone please tell me where I am going wrong? That error means that the format of the receipt is incorrect but I am not sure where this is happening between all the format manipulating.
Thank you!
R
Once change your code to
NSString *jsonObjectString = [self encodeBase64:(uint8_t *)transaction.transactionReceipt.bytes
length:transaction.transactionReceipt.length];

IOS: facebook sdk per my own post

I have a question about sdk facebook integration with my iOS app.
In my app I want authenticate the users with the facebook login and it's all clear here
http://developers.facebook.com/docs/tutorials/ios-sdk-tutorial/
In this app the users should post something in their facebook account, as a photo or a message, not complicated yet.
The problem is... is it possible detect the number of comments and like that users receive for their posts? Is there something in facebook sdk that allow to obtain this information?
thanks
Use following code and you can get more idea from Facebook iOS SDK 3.0, implement like action on a url? also.
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);

Need alternative to Facebook Open Graph og.likes action for Facebook page

While attempting to publish a like connection between a Facebook user and a Facebook page (using Facebook's Open Graph og.likes action type) within an iOS app I received the following error:
{"error":{"message":"(#100) Like actions are not yet supported against objects of this type.","type":"OAuthException","code":100}}
After doing a little research I found that open graph like actions can not be published against Facebook pages. My understanding is that my only other option would be to embed the standard like button with a UIWebView.
My question:
Is there anything else I can do to create a similar or meaningful open graph connection between a Facebook user and a Facebook page without using a UIWebView?
Below is some of my code, I successfully used it to publish a like against a non-Facebook page to verify the issue wasn't something else:
if(isFacebookServiceAuthorized)
{
NSLog(#"Facebook service is authorized");
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *accessToken = [defaults valueForKey:#"kSHKFacebookAccessToken"];
id userInfo = [defaults valueForKey:#"kSHKFacebookUserInfo"];
NSString *userID = [userInfo objectForKey:#"id"];
NSLog(#"Access Token: %# and userid: %#", accessToken, userID);
NSString *devID = FACEBOOK_DEV_USERID
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"https://graph.facebook.com/%#/og.likes", devID]];
NSMutableURLRequest *request1 = [NSMutableURLRequest requestWithURL:url];
[request1 setURL:url];
[request1 setHTTPMethod:#"POST"];
NSString *body=[NSString stringWithFormat:#"access_token=%#&object=OBJECT_TO_LIKE", accessToken];
[request1 setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
NSError *error;
NSURLResponse *response;
NSData *data = [NSURLConnection sendSynchronousRequest:request1 returningResponse:&response error:&error];
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"string..:%#",string);
}

Logging in from settings username and password preferences

I have an app that uses webView. In the home screen of a website I want to login using username and password entered by the user in the app's settings option. Currently I have this code which I saw in solution to a similar question asked on this forum. But it isn't working (neither it did for the other guy).
-(IBAction)cachepressed:(id)sender{
NSString *baseurl=[[NSUserDefaults standardUserDefaults] stringForKey:#"url_preference"];
NSString *username= [[NSUserDefaults standardUserDefaults] stringForKey:#"name_preference"];
NSString *password= [[NSUserDefaults standardUserDefaults] stringForKey:#"pswrd_preference"];
NSString* content = [NSString stringWithFormat:#"username=%#&password=%#", username, password];
NSData *data=[content dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postlength=[NSString stringWithFormat:#"%d",[data length]];
NSString *loginpage= [baseurl stringByAppendingString:#"/index.php?title=Special:UserLogin"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:loginpage]];
[request setHTTPMethod:#"POST"];
[request setValue:postlength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:data];
NSError *error=nil;
NSURLResponse *response=nil;
NSData *result=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *HTMLString = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
[webView loadHTMLString:HTMLString baseURL:[NSURL URLWithString:loginpage]];
}
I am not too sure about the two lines of code starting with [request setValue...]. Can somebody suggest a solution to this? It would be a great help. Thanks in anticipation.
This depends a lot on how the authentication is done on the website.
Based on what I can figure from your question, the code you posted sends values for the fields named "username" and "password" to the index.php?title=Special:UserLogin page using POST.
You need to make sure that everything is set accordingly.
1. Are your fields name the same on the website?
Maybe the login form uses different field names, not username and password. Check the source code and see if the input names are indeed "username" and "password"
2. Does your host allow posting data from a different source?
I used to set mine so no POST request would work if they didn't originate from my server, so POSTing data from an iPad would not have functioned.
Is this the case for you too?
3. The login process is really done by posting data to that page?
Maybe on the website the authentication is done using AJAX on a different php page and then you get redirected to index.php?title=Special:UserLogin, I've seen such cases in the past.
Bottom line is that you need to know exactly how the login is done on the website before doing it inside a webview. Correct me if I'm wrong, but based on your post it doesn't seem to be the case here

Resources