get share link (file link) for BOX in iOS - ios

I am using box SDK V2 and the folder picker present in the sample app. I do not need any upload or download facility. I just need to get the file's ShareLink.
I am successfully displaying the filename and everything but not the share link.
I am getting a NULL.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
BoxItem *item = (BoxItem *)[self.folderItemsArray objectAtIndex:[indexPath row]];
NSLog(#"item type : %# : %# : %# ", item.type, item.name, item.sharedLink);
}
Am using this code.(from sample app)
I am getting results like:
1.item type : file : dummy.pdf : (null)
2. item type : file : presentations-tips.ppt : (null)
I am not getting the sharedlink.
first reaction: may be sharedlinks are not created for those files, So:
I went to my box account and created share links for those files through my desktop.
and rechecked. but got same result.
I need the shared link badly. Please help. Thanks in advance

I got the solution for getting shared link of file. Write following lines of code where you want to get shared link.
BoxFileBlock successfulShare = ^(BoxFile *file)
{
dispatch_sync(dispatch_get_main_queue(), ^{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"File Share Successful" message:[NSString stringWithFormat:#"Shared link: %#", [file.sharedLink objectForKey:#"url"]] delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
});
};
BoxAPIJSONFailureBlock failedShare = ^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSDictionary *JSONDictionary)
{
BOXLog(#"status code: %i", response.statusCode);
BOXLog(#"share response JSON: %#", JSONDictionary);
};
BoxFilesRequestBuilder *builder = [[BoxFilesRequestBuilder alloc] init];
BoxSharedObjectBuilder *sharedBuilder = [[BoxSharedObjectBuilder alloc] init];
sharedBuilder.access = BoxAPISharedObjectAccessOpen;
builder.sharedLink = sharedBuilder;
[[BoxSDK sharedSDK].filesManager editFileWithID:YOUR_FILE.modelID requestBuilder:builder success:successfulShare failure:failedShare];

Related

facebook content looks diffrent in wall and home page , after posting the content from iOS app using facebook sdk of iOS

Facebook content looks different in wall and home page , after posting the content from iOS app using facebook sdk of iOS,
Used Code : We are using following code for posting the data in facebook wall.
[NSMutableDictionary dictionaryWithObjectsAndKeys:
#"Found this app ", #"message",
#"AppName", #"name",
#"App Title", #"caption",
#"Description data", #"description",
#"Link URL", #"link",
#"Image URL", #"picture",nil];
// create the connection object.
FBRequestConnection *newConnection = [[[FBRequestConnection alloc] initWithTimeout:kRequestTimeoutInterval] autorelease];
// create the request object, using the fbid as the graph path as an alternative the request* static methods of the
// FBRequest class could be used to fetch common requests, such as /me and /me/friends
FBRequest *request=[[[FBRequest alloc] initWithSession:activeSession
graphPath:#"me/feed"
parameters:params
HTTPMethod:#"POST"] autorelease];
Detail: When we are going to post this data and link url ia available then content are looks different in home screen and profile screen .
Instead od App Name is display the Link URL title in home page but in profile page it display right content like App Title.
It happen only posting from iOS app , it looks good from Android app.
Please help Me tikamchandrakar#gmail.com or tikam.chandrakar#xymob.com
Let me know if any thing is not clear.
Thanks
Try This code. It works Perfect for me -
// Helper method to request publish permissions and post.
- (void)requestPermissionAndPost {
[FBSession.activeSession requestNewPublishPermissions:[NSArray arrayWithObject:#"publish_actions"]
defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session, NSError *error) {
if (!error && [FBSession.activeSession.permissions indexOfObject:#"publish_actions"] != NSNotFound) {
// Now have the permission
[self postOpenGraphAction];
} else if (error){
// Facebook SDK * error handling *
// if the operation is not user cancelled
if (error.fberrorCategory != FBErrorCategoryUserCancelled) {
// [self presentAlertForError:error];
}
}
}];
}
// Creates the Open Graph Action.
- (void)postOpenGraphAction {
NSString *pageId = #"";
if ([pageIdArray count] > 0) {
pageId = [[pageIdArray objectAtIndex:0] objectForKey:#"page_id"];
}else{
pageId = #"";
}
//http://mistoh.com/mistohws/CategoriesIcon/CategoryIcon_%1$s.png
[FBRequestConnection startWithGraphPath:#"me/feed"
parameters:#{
#"link":#"http://mistoh.com/mistohws/CategoriesIcon/CategoryIcon_1.png",
#"message":[NSString stringWithFormat:#"I just shared a Mistoh at %#",self.mistohNameStr],
#"place":[NSString stringWithFormat:#"%#",pageId],
#"name":[NSString stringWithFormat:#"%#",self.mistohNameStr],
#"description":[NSString stringWithFormat:#"%#",self.mistohDescStr],
#"address":[NSString stringWithFormat:#"%#",self.mistohAddressStr],
#"tags":[NSString stringWithFormat:#"%#",self.selectedFriendsStr]
}
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
//verify result
if (!error) {
[[[UIAlertView alloc] initWithTitle:#"Shared Mistoh Successfully!!"
message:#""
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil]
show];
}else{
[[[UIAlertView alloc] initWithTitle:#"Error"
message:#"Error while sharing mistoh with friends."
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil]
show];
NSLog(#"Error : %#",[error description]);
}
}];
}
It looks good on facebook wall and timeline. Thank You..

Using STTwitter Library how can I attach an image

I'm kind of new on objective c, and I'm trying to do a twitter client. I'm using the STTwitter API. I'm using the for tweeting the method :
[twitter postStatusUpdate:twitterPostTweetText
inReplyToStatusID:nil
mediaURL:_twitterPostMediaURL
placeID:nil
latitude:latitud
longitude:longitud
successBlock:^(NSDictionary *status) {
self->twitterPostTweetText = #"";
self->twitterPostTweetStatus = #"OK";
self->latitud = nil;
self->longitud = nil;
self.twitterPostMediaURL = nil;
} errorBlock:^(NSError *error) {
self->twitterPostTweetStatus = error ? [error localizedDescription] : #"Unknown error";
}];
but it says that for sending an image attached I have to use NSUrl but I can't figure out how does it work. I want to send an image that I take with the camera roll.
Please, any ideas?
Use an NSURL instance representing the file path.
See the example in STTwitter demo https://github.com/nst/STTwitter/blob/master/demo_osx/STTwitterDemoOSX/STClientVC.m#L33-L48

iOS: Canvas URL error when posting to wall

Please see the 29th December update notes at the bottom of the page.
Hi I'm doing maintanance work on someone else's iOS project at work (which is kind of soul destroying because they haven't documented their code).
The problem is that after the user logs in, attempting to share a post to the wall always results in
error 100: "The post's links must direct to the application's connect or canvas URL".
I've searched for the past 2 hours and haven't found any results specifically for iOS (but plenty for wordpress, which didn't help)
Any ideas what might be causing this.
Here's the overseas developer code for posting to the wall:
-(void)uploadPropertyDetailsOnFacebookWall
{
[FBSettings setLoggingBehavior:[NSSet setWithObjects:FBLoggingBehaviorFBRequests, FBLoggingBehaviorFBURLConnections, nil]];
NSString* photoURL = #"";
NSString *strFullPropertyDetailLink=#"";
if (!kIsListOnce) {
photoURL = [currentItem objectForKey:#"Photo1FeaturedURL"];
strFullPropertyDetailLink=[currentItem objectForKey:#"FullDisplayLink"];
}
else {
strFullPropertyDetailLink=[currentItem objectForKey:#"FullDisplayLink"];
NSArray* list = [[currentItem objectForKey:#"objects"] objectForKey:#"img_small"];
;
if ([list count] > 0) {
photoURL = [list objectAtIndex:0];
}
}
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSString *strLinkOfApp=(NSString *)[Utils config:KiTunesstoreAppLink]; //strFullPropertyDetailLink,
NSDictionary *postParams =
[[NSMutableDictionary alloc] initWithObjectsAndKeys:
strFullPropertyDetailLink, #"link",
photoURL, #"picture",
[Utils config:kTextAgentName], #"name",
strAddress, #"caption",
[currentItem objectForKey:#"Description"], #"description",
nil];
[FBRequestConnection startWithGraphPath:#"me/feed"
parameters:postParams
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection,
id result,
NSError *error)
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSString *alertText;
NSLog(#"%#",error);
if (error) {
NSDictionary *dict=[error userInfo];
NSLog(#"%#",dict);
NSDictionary *dictJSON=[dict objectForKey:#"com.facebook.sdk:ParsedJSONResponseKey"];
NSDictionary *dictBody=[dictJSON objectForKey:#"body"];
NSDictionary *dictError=[dictBody objectForKey:#"error"];
NSString *strCode=[[dictError objectForKey:#"code"] description];
if([strCode isEqualToString:#"200"])
{
alertText = #"You have not authorized the application to perform this publish action";
}else{
alertText = [#"An error ocurred: " stringByAppendingString:error.description];
alertText=[alertText stringByAppendingString: strFullPropertyDetailLink];
}
} else {
alertText = [NSString stringWithFormat:
#"Property details has been successfully shared on your Facebook Wall"];
}
[[[UIAlertView alloc] initWithTitle:#"Result"
message:alertText
delegate:nil
cancelButtonTitle:#"OK!"
otherButtonTitles:nil] show];
// Show the result in an alert
}];
}
Here's the error I keep getting:
Error Domain=com.facebook.sdk Code=5 "The operation couldn’t be completed(com.facebook.sdk error 5.)" UserInfo=0x1d548710 {com.facebook.sdk:ParsedJSONResponseKey={
body = {
error = {
code = 100;
message = "(#100) The post's links must direct to the application's connect or canvas URL.";
type = OAuthException;
};
};
code = 400;
}, com.facebook.sdk:HTTPStatusCode=400}
2013-08-02 12:06:12.806 RealEstate[385:907] {
"com.facebook.sdk:HTTPStatusCode" = 400;
"com.facebook.sdk:ParsedJSONResponseKey" = {
body = {
error = {
code = 100;
message = "(#100) The post's links must direct to the application's connect or canvas URL.";
type = OAuthException;
};
};
code = 400;
};
}
Please help, I have done more research online since my initial posting, and still can't find the answer.
Update Dec 17th:
I am using SDK 3.1.1. I'd like to avoid having to update, as I'm maintaining someone else's code.
Using me/feed, in a fbrequestconnection, any additional paramater aside from "message", crashes the app.
I've also tried linking the app to a test account with settings suggested by other stack overflow users viewable here
I've also disabled post streaming security
Other Questions
Am I missing something in linking up the app to Facebook?
Why won’t it detect that the “link” parameter is the same as the canvas url?
I've been struggling with posting to facebook wall too.
Why don't you use the facebook SDK instead of the API?
There are two ways to post to facebook wall using the SDK
Via Feed Dialog
or
Via Share Dialog
The Feed Dialog is very easy to implement and you can control what you want to post through the parameters you send, the only bad thing is that the parameters are limited.
The Share Dialog uses OpenGraph and requires the user to have the facebook APP installed, you also have to create an action in app developer page in facebook so your app knows what to do with that action.
The good part is that you can share almost all that you want.
I suggest you check the Feed Dialog if you want a simple facebook share, it's the easiest way.
Edit
NSString *message = [NSString stringWithFormat:#"%#%#/%#",domain,TypeName,[object alias]];
// Put together the dialog parameters
NSMutableDictionary *params =
[NSMutableDictionary dictionaryWithObjectsAndKeys:
#"TITLE", #"description",
message, #"link",
[object image],#"picture",
nil];
// Invoke the dialog
[FBWebDialogs presentFeedDialogModallyWithSession:nil
parameters:params
handler:
^(FBWebDialogResult result, NSURL *resultURL, NSError *error) {
if (error) {
// Error launching the dialog or publishing a story.
//NSLog(#"Error publishing story.");
} else {
if (result == FBWebDialogResultDialogNotCompleted) {
// User clicked the "x" icon
//NSLog(#"User canceled story publishing.");
} else {
// Handle the publish feed callback
NSDictionary *urlParams = [self parseURLParams:[resultURL query]];
if (![urlParams valueForKey:#"post_id"]) {
// User clicked the Cancel button
//NSLog(#"User canceled story publishing.");
} else {
// User clicked the Share button
NSString *msg = #"Partilhado com sucesso";
//NSLog(#"%#", msg);
// Show the result in an alert
[[[UIAlertView alloc] initWithTitle:#"Aviso"
message:msg
delegate:nil
cancelButtonTitle:#"OK!"
otherButtonTitles:nil]
show];
}
}
}
}];

How can I decode the UIPasteboard type "apple web archive pasteboard" web content , and sync this with evernote api?

First , i try to get the webResourceData from UIPasteboard :
if ([[pasteboard pasteboardTypes] containsObject:#"Apple Web Archive pasteboard type"]) {
NSData* archiveData = [[UIPasteboard generalPasteboard] valueForPasteboardType:#"Apple Web Archive pasteboard type"];
if (archiveData)
{
if (DEBUG) [self checkPasteboard];
NSError* error = nil;
id webArchive = [NSPropertyListSerialization propertyListWithData:(NSData *)archiveData options:NSPropertyListImmutable format:NULL error:&error];
if (error) {
//TODO:
DLog(#"format error!");
}
NSDictionary* webMainResource = [webArchive objectForKey:#"WebMainResource"];
NSData * webResourceData = [dic objectForKey:#"WebResourceData"];
}
}
then , i try to create a not with this data:
NSData *dataHash = [webResourceData enmd5];
EDAMData *edamData = [[EDAMData alloc] initWithBodyHash:dataHash size:webResourceData.length body:webResourceData];
EDAMResource* resource = [[EDAMResource alloc] initWithGuid:nil noteGuid:nil data:edamData mime:#"text/html" width:0 height:0 duration:0 active:0 recognition:0 attributes:nil updateSequenceNum:0 alternateData:nil];
NSString *noteContent = [NSString stringWithFormat:#"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
"<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">"
"<en-note>"
"<span style=\"font-weight:bold;\">Hello Evernote.</span>"
"</en-note>"];
NSMutableArray* resources = [NSMutableArray arrayWithArray:#[resource]];
EDAMNote *newNote = [[EDAMNote alloc] initWithGuid:nil title:#"Test note" content:noteContent contentHash:nil contentLength:noteContent.length created:0 updated:0 deleted:0 active:YES updateSequenceNum:0 notebookGuid:nil tagGuids:nil resources:resources attributes:nil tagNames:nil];
[[EvernoteNoteStore noteStore] setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
DLog(#"Total bytes written : %lld , Total bytes expected to be written : %lld",totalBytesWritten,totalBytesExpectedToWrite);
}];
[[EvernoteNoteStore noteStore] createNote:newNote success:^(EDAMNote *note) {
DLog(#"Note created successfully.");
//TODO: need delete the cell
} failure:^(NSError *error) {
DLog(#"Error creating note : %#",error);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:[error.userInfo objectForKey:#"NSLocalizedDescription"]
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}];
the problem is what I can see from Evernote is a attachment but not the web content...
To show the web content you will need to embed it in the ENML, you don't need to add it to the Resources. Here is a simple example :
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">
<en-note>
<h1>
Simple HTML note
</h1>
</en-note>

Using the Google APIs with OAuth 2.0 for gmail login in iPhone

I have found a services from Google which provides to access to Google APIs for various Google Services. I could set up a project in iPhone and create API access for iOS applications (via OAuth2.0) and native applications. I wanted to use the native API for my iPhone app. It API gives me email,fullname,firstname,lastname,google_id,gender,dob,profile_image. How do I use these in my iPhone Application, Any sample apps, snippets available?
Please help me.
Here is my code :
-(void) loadGmail_Login
{
NSString *keychainItemName = nil;
if ([self shouldSaveInKeychain]) {
keychainItemName = kKeychainItemName;
}
// For GTM applications, the scope is available as
NSString *scope = #"http://www.google.com/m8/feeds/";
// ### Important ###
// GTMOAuthViewControllerTouch is not designed to be reused. Make a new
// one each time you are going to show it.
// Display the autentication view.
GTMOAuthAuthentication *auth;
auth = [GTMOAuthViewControllerTouch authForGoogleFromKeychainForName:kKeychainItemName];
GTMOAuthViewControllerTouch *viewController = [[[GTMOAuthViewControllerTouch alloc]
initWithScope:scope
language:nil
appServiceName:keychainItemName
delegate:self
finishedSelector:#selector(viewController:finishedWithAuth:error:)] autorelease];
// You can set the title of the navigationItem of the controller here, if you want.
// Optional: display some html briefly before the sign-in page loads
NSString *html = #"<html><body bgcolor=silver><div align=center>Loading sign-in page...</div></body></html>";
[viewController setInitialHTMLString:html];
[[self navigationController] pushViewController:viewController animated:YES];
}
- (void)viewController:(GTMOAuthViewControllerTouch *)viewController
finishedWithAuth:(GTMOAuthAuthentication *)auth
error:(NSError *)error
{
if (error != nil)
{
// Authentication failed (perhaps the user denied access, or closed the
// window before granting access)
NSLog(#"Authentication error: %#", error);
NSData *responseData = [[error userInfo] objectForKey:#"data"]; // kGTMHTTPFetcherStatusDataKey
if ([responseData length] > 0) {
// show the body of the server's authentication failure response
NSString *str = [[[NSString alloc] initWithData:responseData
encoding:NSUTF8StringEncoding] autorelease];
NSLog(#"%#", str);
}
[self setAuthentication:nil];
}
else
{
// save the authentication object
[self setAuthentication:auth];
// Just to prove we're signed in, we'll attempt an authenticated fetch for the
// signed-in user
[self doAnAuthenticatedAPIFetch];
}
}
- (void)doAnAuthenticatedAPIFetch
{
NSString *urlStr;
// Google Contacts feed
//
// https://www.googleapis.com/oauth2/v2/userinfo
urlStr = #"http://www.google.com/m8/feeds/contacts/default/thin";
NSURL *url = [NSURL URLWithString:urlStr];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[mAuth authorizeRequest:request];
NSError *error = nil;
NSURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
if (data) {
// API fetch succeeded
NSString *str = [[[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding] autorelease];
NSLog(#"API response: %#", str);
GGCXml_Adaptor *localAlphabetXMLParser = [[GGCXml_Adaptor alloc] init];
[localAlphabetXMLParser processBooksXML:data];
[localAlphabetXMLParser release];
// [self updateUI];
} else {
// fetch failed
NSLog(#"API fetch error: %#", error);
}
}
- (void)setAuthentication:(GTMOAuthAuthentication *)auth {
[mAuth autorelease];
mAuth = [auth retain];
}
First you will need to get token from Google API, For this 1st step you will have to follow this tutorial and in the end of this link there is whole source code for iOS for getting token from google API
http://technogerms.com/login-with-google-using-oauth-2-0-for-ios-xcode-objective-c/
Then in the next step you have to send that token to Google API to request user Data, I just needed the first step So I am sharing my searchings
Try this Tutorial and Source code Link.. It's works fine for me.
1. Tutorial Reference: http://technogerms.com/login-with-google-using-oauth-2-0-for-ios-xcode-objective-c/
2. Api Reference : https://code.google.com/apis/console/
3. Source code: https://github.com/emysa341/Login-with-gmail-google-g--using-oath-2.0-protocol/archive/master.zip
i think this will help anybody else
Follow the below steps to integrate gmail with your application .
1.Add following classes to you project .
GTMHTTPFetcher.h , GTMHTTPFetcher.m ,GTMOAuth2Authentication.h, GTMOAuth2Authentication.m,GTMOAuth2SignIn.h,GTMOAuth2SignIn.m,GTMOAuth2ViewControllerTouch.h,GTMOAuth2ViewControllerTouch.m,GTMOAuth2ViewTouch.xib,SBJSON.h , SBJSON.m
you will get these classes here : https://github.com/jonmountjoy/Force.com-iOS-oAuth-2.0-Example
Note : if you are working under ARC Environment then you have to disable the ARC for following files :
GTMHTTPFetcher.m , GTMOAuth2Authentication.m , GTMOAuth2SignIn.m, GTMOAuth2ViewControllerTouch.m
To disable ARC for source files in Xcode 4, select the project and the target in Xcode. Under the target "Build Phases" tab, expand the Compile Sources build phase, select the library source files, then press Enter to open an edit field, and type -fno-objc-arc as the compiler flag for those files.
2. add the following frameworks
security.framework , systemConfiguration.framework
3. Register your app to google api console …. here : https://code.google.com/apis/console
Then go to ApiAccess section , create client id for iOS app .
then you will get clientID, ClientSecret and RedirectUrl
**4. Now it's time for coding . . . .**
create a signIn button in your controller and set the action for that . Here when the user click the button SignInGoogleButtonClicked method gets called .
//import GTMOAuth2Authentication , GTMOAuth2ViewControllerTouch
#define GoogleClientID #"paster your client id"
#define GoogleClientSecret #"paste your client secret"
#define GoogleAuthURL #"https://accounts.google.com/o/oauth2/auth"
#define GoogleTokenURL #"https://accounts.google.com/o/oauth2/token"
-(void) SignInGoogleButtonClicked
{
NSURL * tokenURL = [NSURL URLWithString:GoogleTokenURL];
NSString * redirectURI = #"urn:ietf:wg:oauth:2.0:oob";
GTMOAuth2Authentication * auth;
auth = [GTMOAuth2Authentication authenticationWithServiceProvider:#"google"
tokenURL:tokenURL
redirectURI:redirectURI
clientID:GoogleClientID
clientSecret:GoogleClientSecret];
auth.scope = #"https://www.googleapis.com/auth/plus.me";
GTMOAuth2ViewControllerTouch * viewcontroller = [[GTMOAuth2ViewControllerTouch alloc] initWithAuthentication:auth
authorizationURL:[NSURL URLWithString:GoogleAuthURL]
keychainItemName:#"GoogleKeychainName" delegate:self
finishedSelector:#selector(viewController:finishedWithAuth:error:)];
[self.navigationController pushViewController:viewcontroller animated:YES];
}
//this method is called when authentication finished
- (void)viewController:(GTMOAuth2ViewControllerTouch * )viewController finishedWithAuth:(GTMOAuth2Authentication * )auth error:(NSError * )error
{
if (error != nil) {
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:#"Error Authorizing with Google"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
else
{
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:#"Alert !"
message:#"success"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
}

Resources