NSURL *baseURL = [NSURL URLWithString:@"https://graph.facebook.com/"]; AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:baseURL]; NSString *link = [NSString stringWithFormat:@"/%@/likes", @"OBJECT_ID"]; NSDictionary *params = @{@"access_token" : [[[FBSession activeSession] accessTokenData] accessToken]}; [httpClient postPath:link parameters:params success:^(AFHTTPRequestOperation *op, id result) { NSLog(@"result %@", result); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"error %@", error); }];That's it, don't hesitate to comment, to share your knowledge and to correct me.
Friday, April 5, 2013
Thursday, January 24, 2013
Twitter for iOS6 without the modal view.
Posted by Polaris on 11:40 PM
Hi,
I guess I got this one from some Stackoverflow question.
Link against Social.framework and accounts.framework.
I guess I got this one from some Stackoverflow question.
Link against Social.framework and accounts.framework.
#import <Accounts/Accounts.h> #import <Social/Social.h> ========================================= ACAccountStore *account = [[ACAccountStore alloc] init]; ACAccountType *accountType = [account accountTypeWithAccountTypeIdentifier: ACAccountTypeIdentifierTwitter]; [account requestAccessToAccountsWithType:accountType options:nil completion:^(BOOL granted, NSError *error) { if (granted == YES) { NSArray *arrayOfAccounts = [account accountsWithAccountType:accountType]; if ([arrayOfAccounts count] > 0) { ACAccount *twitterAccount = [arrayOfAccounts lastObject]; NSDictionary *message = @{@"status": @”My First Twitter post from iOS6”}; NSURL *requestURL = [NSURL URLWithString:@"http://api.twitter.com/1/statuses/update.json"]; SLRequest *postRequest = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodPOST URL:requestURL parameters:message]; postRequest.account = twitterAccount; [postRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) { NSLog(@"Twitter HTTP response: %i", [urlResponse statusCode]); }]; } } }];That's it, don't hesitate to comment, to share your knowledge and to correct me.
Twitter for iOS5 without the modal view: (works for iOS6 as well)
Posted by Polaris on 11:29 PM
Hi,
I found this here.
Link the project against Twitter.framework and accounts.framework.
I found this here.
Link the project against Twitter.framework and accounts.framework.
#import <Twitter/Twitter.h> #import <Accounts/Accounts.h> ============================================= - (void)postToTwitter { // Create an account store object. ACAccountStore *accountStore = [[ACAccountStore alloc] init]; // Create an account type that ensures Twitter accounts are retrieved. ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier: ACAccountTypeIdentifierTwitter]; // Request access from the user to use their Twitter accounts. [accountStore requestAccessToAccountsWithType:accountType withCompletionHandler:^(BOOL granted, NSError *error) { if(granted) { // Get the list of Twitter accounts. NSArray *accountsArray = [accountStore accountsWithAccountType:accountType]; if ([accountsArray count] > 0) { // Grab the initial Twitter account to tweet from. ACAccount *twitterAccount = [accountsArray objectAtIndex:0]; TWRequest *postRequest = nil; postRequest = [[TWRequest alloc] initWithURL:[NSURL URLWithString: @"http://api.twitter.com/1/statuses/update.json"] parameters:[NSDictionary dictionaryWithObject: @"The message to post" forKey:@"status"] requestMethod:TWRequestMethodPOST]; // Set the account used to post the tweet. [postRequest setAccount:twitterAccount]; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) { [postRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) { dispatch_async(dispatch_get_main_queue(), ^(void) { if ([urlResponse statusCode] == 200) { NSLog(@"Successful"); }else { NSLog(@"Failed"); } }); }]; }); } else { [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=TWITTER"]]; } } }]; }That's it, don't hesitate to comment, to share your knowledge and to correct me.
Sunday, December 9, 2012
Android, density independent pixel (dp) to pixels(px)
Posted by Polaris on 6:03 PM
It's highly recommended to use (dp/dip) when defining UI layout, to express layout dimensions or position in a density-independent way.
But, how can we specify the dimensions in (dp) programmatically?
The answer is:
float android.util.TypedValue.applyDimension(int unit, float value, DisplayMetrics metrics)
Where (as mentioned in the documentation):
unit is the unit to convert from.
value is the value to apply the unit to.
metrics is the current display metrics to use in the conversion -- supplies display density and scaling information.
Example:
TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, <whatever dp value>, getResources().getDisplayMetrics());That's it, don't hesitate to comment, to share your knowledge and to correct me.
Posted in Android
Monday, November 26, 2012
iOS6, Rotation.
Posted by Polaris on 3:09 PM
Hi, it's been a while since I posted some thing.
Ok, This post is to fix the auto-rotation problem that has been around since the release of iOS6.
To be clear, the problem is that iOS6 doesn't support - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation; any more. And hence, our apps/code won't behave as expected any more.
In this post, I'll be using three methods/callbacks were introduced in iOS6 which are (BOOL)shouldAutorotate, - (NSUInteger)supportedInterfaceOrientations and (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window.
One important thing to know, (BOOL)shouldAutorotate and (NSUInteger)supportedInterfaceOrientations are added to the topmost parent of the view controller that you want to control its rotation. if, of-course, the view controller is a root view controller, then these methods will be added to it directly.
I hate to repeat myself, but for the sake of clarification, if your root-view-controller is a navigation-controller and you want to control the rotation of a view-controller inside the navigation-controller then (BOOL)shouldAutorotate and (NSUInteger)supportedInterfaceOrientations will be added to the navigation-controller NOT the view-controller itself.
If you have a tab-bar-controller that contains a navigation-controller inside which lies the view-controller that you want to control its rotation, then (BOOL)shouldAutorotate and (NSUInteger)supportedInterfaceOrientations will be added to the topmost parent which is - in this case - the tab-bar-controller.
And your done.
Don't remove -(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation from your code to keep supporting iOS5.
It's recommended to see the documentation for better understanding of the callbacks.
Ok, This post is to fix the auto-rotation problem that has been around since the release of iOS6.
To be clear, the problem is that iOS6 doesn't support - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation; any more. And hence, our apps/code won't behave as expected any more.
In this post, I'll be using three methods/callbacks were introduced in iOS6 which are (BOOL)shouldAutorotate, - (NSUInteger)supportedInterfaceOrientations and (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window.
One important thing to know, (BOOL)shouldAutorotate and (NSUInteger)supportedInterfaceOrientations are added to the topmost parent of the view controller that you want to control its rotation. if, of-course, the view controller is a root view controller, then these methods will be added to it directly.
I hate to repeat myself, but for the sake of clarification, if your root-view-controller is a navigation-controller and you want to control the rotation of a view-controller inside the navigation-controller then (BOOL)shouldAutorotate and (NSUInteger)supportedInterfaceOrientations will be added to the navigation-controller NOT the view-controller itself.
If you have a tab-bar-controller that contains a navigation-controller inside which lies the view-controller that you want to control its rotation, then (BOOL)shouldAutorotate and (NSUInteger)supportedInterfaceOrientations will be added to the topmost parent which is - in this case - the tab-bar-controller.
How to add those methods to a tab-bar-controller or a navigation-controller?
- By subclassing them and overriding the methods inside them.
- By adding them to a category of your tab-bar-controller's or navigation-controller's type. I like this method because, it's simpler specially if the code is already written and i'm doing some slight modifications.
Now, lets take the case of a tab-bar-controller that contains a navigation-controller inside which lies the view-controller that you want to control its rotation as an example. you'll do as follows:
- add (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window to your appdelegate as follows:
- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window { return (UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskLandscapeLeft | UIInterfaceOrientationMaskLandscapeRight); }
- create a category inside your appdelegate as follows:
@implementation tab-view-controller (fixingRotation) - (BOOL)shouldAutorotate { if ([((UINavigationController *)[[((AppDelegate *)[[UIApplication sharedApplication] delegate]).tabBarController viewControllers] objectAtIndex:self.selectedIndex]) .visibleViewController isKindOfClass:[myViewController class]]) { return YES; } else{ return NO; } } -(NSUInteger) supportedInterfaceOrientations { return (UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskLandscapeLeft | UIInterfaceOrientationMaskLandscapeRight); } @end
Don't remove -(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation from your code to keep supporting iOS5.
It's recommended to see the documentation for better understanding of the callbacks.
That's it, don't hesitate to comment, to share your knowledge and to correct me.
Monday, April 23, 2012
Android: Saving cache files on external storage.
Posted by Polaris on 11:20 AM
Hi,
If you want to save some files on external storage and you want those files to be removed on application un-installation, then do as the documentation says ;)
If you want to save some files on external storage and you want those files to be removed on application un-installation, then do as the documentation says ;)
If you're using API Level 8 or greater, use getExternalCacheDir() to open a File
that represents the external storage directory where you should save cache files. If
the user uninstalls your application, these files will be automatically deleted. However,
during the life of your application, you should manage these cache files and remove
those that aren't needed in order to preserve file space.
If you're using API Level 7 or lower, use getExternalStorageDirectory() to open a File
that represents the root of the external storage, then write your cache data in the following
directory:
/Android/data/<package_name>/cache/
The <package_name> is your Java-style package name, such as "com.example.android.app".
Unfortunately, our apps can not receive un-install intent. So, this is the best way to do that.
That's it, don't hesitate to comment, to share your knowledge and to correct me.
Posted in Android
Tuesday, April 17, 2012
Android: Create an image Viewer using ViewPager.
Posted by Polaris on 1:12 AM
Hi,
This post is for those guys digging the Internet trying to find out how to create an image viewer. And I managed to do that using ViewPager.
First, you'll need to download the support package using the SDK manager.
Then, set up the project to use the library, as mentioned here. OR, if you use Eclipse, you can simply right click your project > Android Tools > Add Compatibility Library.
I'll use the project that we created in the previous tutorial to get a horizontal list of images and I'll make some modifications to get to our target.
So, the main layout will be as follows.
main.xml
This post is for those guys digging the Internet trying to find out how to create an image viewer. And I managed to do that using ViewPager.
First, you'll need to download the support package using the SDK manager.
Then, set up the project to use the library, as mentioned here. OR, if you use Eclipse, you can simply right click your project > Android Tools > Add Compatibility Library.
I'll use the project that we created in the previous tutorial to get a horizontal list of images and I'll make some modifications to get to our target.
So, the main layout will be as follows.
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<HorizontalScrollView android:layout_width="fill_parent"
android:layout_height="wrap_content">
<LinearLayout android:id="@+id/_linearLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
</LinearLayout>
</HorizontalScrollView>
<android.support.v4.view.ViewPager android:id="@+id/_viewPager"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#000000"
android:visibility="gone" />
</RelativeLayout>
cell.xml
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linearLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ImageView android:id="@+id/_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView android:id="@+id/_imageName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"/>
</LinearLayout>
We need to create a class that extends PagerAdapter - which is a base class that provide the adapter to populate pages inside of a ViewPager - as mentioned here.
import android.app.Activity;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.ImageView;
public class GalleryPagerAdapter extends PagerAdapter {
private Activity activity;
private int[] drawableIDs;
public GalleryPagerAdapter(Activity activity,int[] drawableIDs){
this.activity = activity;
this.drawableIDs = drawableIDs;
}
@Override
public int getCount() {
return drawableIDs.length;
}
/**
* Create the page for the given position. The adapter is responsible
* for adding the view to the container given here, although it only
* must ensure this is done by the time it returns from
* {@link #finishUpdate()}.
*
* @param container The containing View in which the page will be shown.
* @param position The page position to be instantiated.
* @return Returns an Object representing the new page. This does not
* need to be a View, but can be some other container of the page.
*/
@Override
public Object instantiateItem(View collection, int position) {
ImageView imageView = new ImageView(activity);
imageView.setBackgroundResource(drawableIDs[position]);
((ViewPager) collection).addView(imageView,0);
return imageView;
}
/**
* Remove a page for the given position. The adapter is responsible
* for removing the view from its container, although it only must ensure
* this is done by the time it returns from {@link #finishUpdate()}.
*
* @param container The containing View from which the page will be removed.
* @param position The page position to be removed.
* @param object The same object that was returned by
* {@link #instantiateItem(View, int)}.
*/
@Override
public void destroyItem(View collection, int position, Object view) {
((ViewPager) collection).removeView((ImageView) view);
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view==((ImageView)object);
}
/**
* Called when the a change in the shown pages has been completed. At this
* point you must ensure that all of the pages have actually been added or
* removed from the container as appropriate.
* @param container The containing View which is displaying this adapter's
* page views.
*/
@Override
public void finishUpdate(View arg0) {}
@Override
public void restoreState(Parcelable arg0, ClassLoader arg1) {}
@Override
public Parcelable saveState() {
return null;
}
@Override
public void startUpdate(View arg0) {}
}
And finally, the activity.
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class TestingActivity extends Activity {
// mainLayout is the child of the HorizontalScrollView ...
private LinearLayout mainLayout;
// this is an array that holds the IDs of the drawables ...
private int[] images = {R.drawable.dd1, R.drawable.dd2,
R.drawable.dd3, R.drawable.dd4, R.drawable.dd5, R.drawable.dd6, R.drawable.dd7};
private View cell;
private TextView text;
private ViewPager viewPager;
@Override
public void onBackPressed() {
if(viewPager != null && viewPager.isShown()){
viewPager.setVisibility(View.GONE);
}
else{
super.onBackPressed();
}
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
viewPager = (ViewPager) findViewById(R.id._viewPager);
mainLayout = (LinearLayout) findViewById(R.id._linearLayout);
for (int i = 0; i < images.length; i++) {
cell = getLayoutInflater().inflate(R.layout.cell, null);
final ImageView imageView = (ImageView) cell.findViewById(R.id._image);
imageView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
viewPager.setVisibility(View.VISIBLE);
viewPager.setAdapter
(new GalleryPagerAdapter(TestingActivity.this, images));
viewPager.setCurrentItem(v.getId());
}
});
imageView.setId(i);
text = (TextView) cell.findViewById(R.id._imageName);
imageView.setImageResource(images[i]);
text.setText("Image#"+(i+1));
mainLayout.addView(cell);
}
}
}
That's it, don't hesitate to comment, to share your knowledge and to correct me.
Posted in Android
Subscribe to:
Posts (Atom)
Implement a (Like) action for any object on Facebook (except the pages) using AFNetworking.