How to translate the object c into rubymotion to fetch facebook user’s information - rubymotion

I tried to translate part of the objective-c but I still stuck at part of them
any idea ? Thanks so much
objective c version
if ([FBSDKAccessToken currentAccessToken]) {
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:#"picture",#"fields",nil];
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:#"me"
parameters:params
HTTPMethod:#"GET"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
id result,
NSError *error) {
UIImage * downloadedImage = [UIImage imageWithData:pictureData];
dispatch_async(dispatch_get_main_queue(), ^{
self.profilePictureImageView.image = downloadedImage;
});
}];
}
ruby motion version
if (FBSDKAccessToken.currentAccessToken) {
request = FBSDKGraphRequest.alloc.initWithGraphPath("me", parameters:nil, HTTPMethod: "GET")
}

Finally, I came up with the corresponding code in rubymotion
Please correct me directly if anything wrong, it works for me now
part of original objective-c
if ([FBSDKAccessToken currentAccessToken]) {
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:#"me"
parameters:params
HTTPMethod:#"GET"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
id result,
NSError *error) {
}];
}
convert version by ruby_motion_query
def loginButton(loginButton, didCompleteWithResult: result, error: error)
puts result
puts error
if not error
request = FBSDKGraphRequest.alloc.initWithGraphPath("me", parameters:nil, HTTPMethod: "GET")
request.startWithCompletionHandler( lambda{ |connection, user, error|
#DO_ANYTHING_YOU_WANT_FATE_LOGINING_SUCESSFULLY
rmq(#fb_login_button).animate { |btn| btn.move(b: 400) }
#name_label = rmq.append(UILabel, :label_name).get
#name_label.text = "#{user['first_name']} #{user['last_name']}"
rmq(#name_label).animations.fade_in
})
end
end
def loginButtonDidLogOut(loginButton)
#DO_ANYTHING_YOU_WANT_HERE
end

Related

Handling Facebook Graph API result in iOS SDK with Swift

I just want to request data from Facebook's Graph API, e.g. get the current user's basic info.
The Objective-C doc is: https://developers.facebook.com/docs/ios/graph#userinfo
[FBRequestConnection startForMeWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
/* My question: How do I read the contents of "result" in Swift? */
// Success! Include your code to handle the results here
NSLog(#"user info: %#", result);
} else {
// An error occurred, we need to handle the error
// See: https://developers.facebook.com/docs/ios/errors
}
}];
There's no Swift doc yet, and I'm confused about the "result" parameter whose type is "id".
It looks like result contains a dictionary, but it may be nil. In Swift, its type will map to AnyObject?.
So, in Swift, you could do something like:
// Cast result to optional dictionary type
let resultdict = result as? NSDictionary
if resultdict != nil {
// Extract a value from the dictionary
let idval = resultdict!["id"] as? String
if idval != nil {
println("the id is \(idval!)")
}
}
This can be simplified a bit:
let resultdict = result as? NSDictionary
if let idvalue = resultdict?["id"] as? String {
println("the id value is \(idvalue)")
}
Just remember it is not a dictionary all the way down, it is combinations of dictionaries and arrays.
FBRequestConnection.startWithGraphPath("me?fields=feed", completionHandler: { (connection, result, error) -> Void in
if( error == nil){
let fbGraphObject = result as FBGraphObject
let feed = fbGraphObject.objectForKey("feed") as NSMutableDictionary
let data = feed.objectForKey("data") as NSMutableArray
let postDescription = data[0].objectForKey("description") as String
//println( post )
self.fbu.initialUserFeed = feed
self.performSegueWithIdentifier("SelectStreams", sender: self)
}else
{
//TODO Allert to user that something went wrong
println(error)
}
})
I got confused about this in the beginning
This is a simpler way:
let params: [NSObject : AnyObject] = ["redirect": false, "height": 800, "width": 800, "type": "large"]
let pictureRequest = FBSDKGraphRequest(graphPath: "me/picture", parameters: params, HTTPMethod: "GET")
pictureRequest.startWithCompletionHandler({
(connection, result, error: NSError!) -> Void in
if error == nil {
print("\(result)")
let dictionary = result as? NSDictionary
let data = dictionary?.objectForKey("data")
let urlPic = (data?.objectForKey("url"))! as! String
print(urlPic)
} else {
print("\(error)")
}
})
}

Can not get friends name, pic_quare from Facebook in iOS?

When I am Fetching name and pic_square from my friend list the it shows the following error.
Error: The operation couldn’t be completed. (com.facebook.sdk error 5.)
FBSDKLog: Error: HTTP status code: 400
FBSDKLog: Response <#1386> <Error>:
The operation couldn’t be completed. (com.facebook.sdk error 5.)
{
"com.facebook.sdk:ErrorSessionKey" = "<FBSession: 0x146f1600, state: FBSessionStateOpen, loginHandler: 0x146cca50, appID: 293072694193895, urlSchemeSuffix: , tokenCachingStrategy:<FBSessionTokenCachingStrategy: 0x1468b170>, expirationDate: 2014-07-17 07:47:12 +0000, refreshDate: 2014-05-18 11:14:42 +0000, attemptedRefreshDate: 0001-12-30 00:00:00 +0000, permissions:(\n status,\n permission\n)>";
"com.facebook.sdk:HTTPStatusCode" = 400;
"com.facebook.sdk:ParsedJSONResponseKey" = (
{
body = {
error = {
code = 606;
message = "(#606) The global ID 100003190599973 is not allowed. Please use the application specific ID instead.";
type = OAuthException;
};
};
code = 400;
}
);
}
here I used the code for retrieving the the required information
NSString *query = [NSString stringWithFormat:#"select name, pic_square from user where uid = %#", curId];
NSDictionary *queryParam = [NSDictionary dictionaryWithObjectsAndKeys:query, #"q", nil];
// Make the API request that uses FQL
[FBRequestConnection startWithGraphPath:#"/fql" parameters:queryParam HTTPMethod:#"GET"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error)
{
if (error)
NSLog(#"Error: %#", [error localizedDescription]);
else
{
[namePicArray addObject:result[#"data"]];
}
}];
Thanks in advance.

Uploading multiple binary items as part of a batch call on iOS

I'm trying to make post with more than a photo in Fb using batch request but I keep getting timeout errors from Fb server...
This is my code ..
UIImage *imgFile1 = [UIImage imageNamed:#"iTGps.png"];
NSData *imageData = UIImageJPEGRepresentation(imgFile1, 0.5);
NSString *jsP1 = [NSString stringWithFormat:#"{ \"method\": \"POST\", \"relative_url\": \"me/photos\",\"body\":\"message=My cat photo\",\"attached_files\":\"%#\"}",imageData];
NSString *jsonRequestsArray = [NSString stringWithFormat:#"[%#,%#,%#]",jsP1,jsP1,jsP1];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObject:jsonRequestsArray forKey:#"batch"];
FBRequestConnection *connect = [[FBRequestConnection alloc] initWithTimeout:60];
// do Fb request
FBRequest *request = [FBRequest requestWithGraphPath:#"me/photos"
parameters:params
HTTPMethod:#"POST"];
// add connection
[connect addRequest:request
completionHandler:^(FBRequestConnection *connection,
id result,
NSError *error) {
NSLog(#"Result:%#,%#",result,error);
}];
[connect start];
Where am I doing wrong??
Error code is very long so i cut the middle part (i think is the binary images)
2013-04-28 20:03:32.435 trueGps[1887:1a603] Result:(null),Error Domain=com.facebook.sdk Code=5 "The operation couldn’t be completed. (com.facebook.sdk error 5.)" UserInfo=0x14454010 {com.facebook.sdk:ErrorInnerErrorKey=Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo=0x14492d40 {NSErrorFailingURLStringKey=https://graph.facebook.com/me/photos?sdk=ios&batch=%5B%7B%20%22method%22%3A%20%22POST%22%2C%20%22relative_url%22%3A%20%22me%2Fphotos%22%2C%22body%22%3A%22message%3DMy%20cat%20photo%22%2C%22attached_files ....
NSLocalizedDescription=The request timed out., NSUnderlyingError=0x2a90f620 "The request timed out."}, com.facebook.sdk:HTTPStatusCode=200}
i solve the problem .. but still have more post with only a photo in every one..
NSString *rel_url = [NSString stringWithFormat:#"%#/photos",nomeAlbum];
NSString *jsP1 = [NSString stringWithFormat:#"{ \"method\": \"POST\", \"relative_url\": \"%#\", \"body\": \"message=My_cat_photo\", \"attached_files\": \"file1\" }",rel_url];
NSString *jsonRequestsArray = [NSString stringWithFormat:#"[%#]",jsP1];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObject:jsonRequestsArray forKey:#"batch"];
[params setObject:imgFile1 forKey:#"file1"];
[FBRequestConnection startWithGraphPath:rel_url
parameters:postParams
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection,
id result,
NSError *error) {
}];

ASIFormDataRequest post type

I need to send RestFul Web Service Request with post type ,post data format is like as below {"Request":"parameters".... }and binary data with same request.Is it possible with ios if possible means explain please?
I don't recommend using the ASIHttpRequest library anymore because it's not getting any updates from the developer , as to how to create a post http request here's an example
NSString *url = #"your webservice base url";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
NSString *param2 = ...//
NSData *binaryData = .... //initilize the binary data you want to send
NSString *bodyString = [NSString stringWithFormat:#"param1=%#&param2=%#",binartData,param2];
[request setValue:[NSString stringWithFormat:#"%d", [bodyString length]] forHTTPHeaderField:#"Content-length"];
[request setHTTPBody:[bodyString dataUsingEncoding:NSASCIIStringEncoding]];//or set the type of encoding agreed with your webservice
NSURLResponse *response = nil;
NSError *error = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *responseString;
if ( responseData && !error){
responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
}

Cannot access web service in iOS

I want to connect with a web service from my iOS app. Previously my URL was http://<domain name>/mobilews/mobilews.asmx. Recently I changed to http://<domain name>/mobilewstest/mobilews.asmx
I have put my URL in info plist file. But after I changed this into new URL I cannot login to that.
NSString *urlString = [NSString stringWithFormat:#"%#%#",serverURL,[queryString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"GET"];
NSHTTPURLResponse *response ;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
int statusCode = [((NSHTTPURLResponse *)response) statusCode];`
Here returnData become nill and statusCode is 0. But this urlString is successfully logged in to the web service when it gives in the browser.
NSURL *url = [NSURL URLWithString:#"YOUR URL HERE"];
NSError *connectionError = nil;
NSData *inData = [NSData dataWithContentsOfURL:url options:NSDataReadingUncached error:&connectionError];
NSInteger code = [connectionError code];
if (code != 0)
{
NSString *locDesc = [NSString stringWithString:[connectionError localizedDescription]];
NSString *locFail = [NSString stringWithString:[connectionError localizedFailureReason]];
NSLog(#"Error: %d %# %#", code, locDesc, locFail);
}
else if ([inData length] == 0)
{
NSLog(#"No data");
}
else{
NSData *resultData = [NSData dataWithContentsOfURL:url];
NSString *responseString = [[NSString alloc]initWithData:resultData encoding:NSUTF8StringEncoding];
}
I see you send a syncronous request... try this its more an easy approach.