7. Step 2: Run the sample
Basic samples
• HelloFacebookSample: combines use of FBLoginView, FBProfilePictureView,
FBFriendsPickerViewController, FBPlacePickerViewController, and FBRequest for
profile access, status updates and photo uploading.
• ProfilePictureSample: demonstrates non-logged-in usage of the
FBProfilePictureView control.
• FriendPickerSample: demonstrates usage of the native multi-friend selector control
to choose amongst the logged-in users' friends.
• PlacePickerSample: demonstrates logged-in usage of the FBPlacePickerView
control.
More in-depth single feature samples
• SessionLoginSample: demonstrates detailed login flow via FBSession.
• JustRequestSample: demonstrates logged in user making a request of Facebook via
FBRequest and FBRequestConnection, including batched requests.
• BooleanOGSample: demonstrates publishing an Open Graph custom action type.
More complete and special-case samples
• Scrumptious: integrated sample app demonstrating the use of login, requests, Place
Picker, Friend Picker, Picture Upload, and Open Graph Publishing.
• SwitchUserSample: demonstrates an approach to allow switching logins between
multiple users - for example, on a shared family iPad.
11. Step 4: Start new X-code Project
Add the Facebook SDK for iOS Framework by dragging the FacebookSDK.frameworkfolder
from the SDK installation folder into the Frameworks section of your Project Navigator.
12. Step 4: Start new X-code Project
Add the Facebook SDK for iOS resource bundle by dragging
theFacebookSDKResources.bundle file from theFacebookSDK.framework/
Resources folder into the Frameworks section of your Project Navigator.
13. Step 4: Start new X-code Project
Add the ''-lsqlite3.0'' SQL library to the list of build dependencies
14. Step 4: Start new X-code Project
Finally, you need to place the Facebook app ID in two places in your application's
main.plist file. Create a key called FacebookAppID with a string value, and add
the app ID there:
250959118344050
15. Step 4: Start new X-code Project
Also, create an array key called URL types with a single array sub-item called URL
Schemes. Give this a single item with your app ID prefixed with fb:
This is used to ensure the application will receive the callback URL of the web-based OAuth flow.
16. Step 5: FACEBOOK Login & Authenticate
FBsession 객체 : login & Authorize manage
• sessionOpenWithPermissions:completionHandler:
함수를 호출하여 퍼미션를 선언하고 세션인증을 받을 콜백 핸들러를 제공
한다.
• Facebook App으로부터 받을 핸들러 구성
• login or error 에대한 콜백핸들러 구현
MyAppViewController : 로그인 후
FBLoginViewController : 로그인 전
17. Step 5: FACEBOOK Login & Authenticate
New File > Object-c class > FBLoginViewController
xib 파일에서 Button & Activity Indicator 추가
18. Step 5: FACEBOOK Login & Authenticate
한번 로그인 성공하고 나면 MYAppViewController 를 보여줄 것이다.
앱이 실행되면 먼저 저장되어있는 session를 체크하여 로그인/로그아웃 화면을 선택
한다.
실질적인 메인화면은 MyAppviewController 가 될것이며
FBLoginViewConroller는 필요할때만 모달로 나타날 것이다.
1. AppDelegate.m 파일에 해더 추가
#import <FacebookSDK/FacebookSDK.h>
2. AppDelegate.m 파일에 FBLoginViewController 파일추가
#import “FBLoginViewController“
19. Step 5: FACEBOOK Login & Authenticate
3.로그인뷰가 모달로 보여질것임으로,,
MyAppViewController needs to be part of a UINavigationController.
AppDelegate.h 파일에 new navigation controller 선언
@interface MyAppDelegate ()
@property (strong, nonatomic)
UINavigationController* navController;
@end
4. AppDelegate.m 파일에 Synthesize this new property
@synthesize navController = _navController;
20. Step 5: FACEBOOK Login & Authenticate
5. AppDelegate.h 파일에 생성시 기본으로 만들어진
@property (strong, nonatomic) MyAppViewController *viewController; 를
@property (strong, nonatomic) MyAppViewController *mainViewController;
로 고친다
6. AppDelegate.m 파일에
modify the synthesized property to have the new name by changing:
@synthesize mainViewController = _mainViewController;
22. Step 5: FACEBOOK Login & Authenticate
9. application:didFinishLaunchingWithOptions: method, change this code:
FBSession을 채크하여 로그인화면 보여줄것인지 판단한는 함수 추가
// See if we have a valid token for the current state.
if (FBSession.activeSession.state == FBSessionStateCreatedTokenLoaded) {
// To-do, show logged in view
} else {
// No, display the login page.
[self showLoginView];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.mainViewController = [[MyAppViewController alloc] initWithNibName:@"MyAppViewController_iPhone" bundle:nil];
self.navController = [[UINavigationController alloc] initWithRootViewController:self.mainViewController];
self.window.rootViewController = self.navController;
[self.window makeKeyAndVisible];
if (FBSession.activeSession.state == FBSessionStateCreatedTokenLoaded) {
// To-do, show logged in view
} else {
// No, display the login page.
[self showLoginView];
}
return YES;
}
23. Step 5: FACEBOOK Login & Authenticate
10. FBLoginViewController.xib attach an action to the
login button & outlet to the activity indicator IN FBLoginViewController.m
27. Step 5: FACEBOOK Login & Authenticate
13. application:didFinishLaunchingWithOptions: method, change this code:
// See if we have a valid token for the current state.
if (FBSession.activeSession.state == FBSessionStateCreatedTokenLoaded) {
// To-do, show logged in view
[self openSession];
} else {
// No, display the login page.
[self showLoginView];
}
14. App Delegate .h 파일에 함수 선언 추가
- (void)openSession;
29. Step 5: FACEBOOK Login & Authenticate
17. FBLoginViewController.m - (void)loginFailed; 함수 구현
- (void)loginFailed
{
// User switched back to the app without authorizing. Stay here, but
// stop the spinner.
[self.spinner stopAnimating];
}
18. FBLoginViewController.h - (void)loginFailed; 함수 선언
- (void)loginFailed;
31. Step 5: FACEBOOK Login & Authenticate
20. Facebook 에 로그인하는동안 App 이나 safari를 통해 컨트롤을 보내고 인증
받은
후에 session 정보를 받아온다.
이것을 수행하는 (BOOL)application:(UIApplication *)application openURL
함수를 AppDelegate.m 파일에 구현
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation
{
return [FBSession.activeSession handleOpenURL:url];
}
21. Facebook 인증중에 사용자가 폰을종료시켜버릴경우 세션도 종료시켜야 함
으로
applicationDidBecomeActive: delegate 메소드에 다음을 추가한다.
if (FBSession.activeSession.state == FBSessionStateCreatedOpening) {
[FBSession.activeSession close]; // so we close our session and start over
}
32. Step 5: FACEBOOK Login & Authenticate
22. MyAppViewController.m 파일에 해더를 추가
#import <FacebookSDK/FacebookSDK.h>
23. MyAppViewController.m 파일의 viewDidLoad 함수에 추가
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]
initWithTitle:@"Logout"
style:UIBarButtonItemStyleBordered
target:self
action:@selector(logoutButtonWasPressed:)];
24. MyAppViewController.m 파일의 logoutButtonWasPressed 함수에 추가
-(void)logoutButtonWasPressed:(id)sender {
[FBSession.activeSession closeAndClearTokenInformation];
}
33. Step 6: Personalize
displaying the user's profile picture and name when they've authenticated.
1) Facebook SDK FBRequest object
2) activeSession on FBSession has been opened, or else provide an explicit FBSession
instance to the FBRequestcalls.
3) requestForMeWithSession that returns an FBRequestobject
4) The user data will be a strongly typed FBGraphUser object
5) Once you've constructed an FBRequest object, you can initiate the API call by invoking
thestartWithCompletionHandler: method.
View 추가후 class 를 FBProfilePictureView로 셋팅
XIB 객체선택후 ctl + 드레그 to 소스코드
35. Step 6: Personalize
User info Display function구현
- (void)populateUserDetails
{
if (FBSession.activeSession.isOpen) {
[[FBRequest requestForMe] startWithCompletionHandler:
^(FBRequestConnection *connection,
NSDictionary<FBGraphUser> *user,
NSError *error) {
if (!error) {
self.userNameLabel.text = user.name;
self.userProfileImage.profileID = user.id;
}
}];
}
}
이함수가 성공적으로 실행되면
FBProfilePictureView 객체의 Property에 정보를 셋팅한다.
36. Step 6: Personalize
로그인 상태에서 정보를 바로 보여주기위한 function구현
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
if (FBSession.activeSession.isOpen) {
[self populateUserDetails];
}
}
페이지 로딩시 이함수가 실행되면서 사용자정보를 바로 보여준다.
37. Step 6: Personalize
업데이트된 사용자 정보를 어느때나 보고 싶다면 Active Session이 바뀔때마다
NSNotificationCenter를 notified하여 제공할수 있다.
1.AppDelegate.h 파일에 다음을 선언한다.
extern NSString *const SCSessionStateChangedNotification;
2.AppDelegate.m 파일에 다음을 추가한다.
NSString *const SCSessionStateChangedNotification =
@"com.solab.FaceBookApiFirst:FBSessionStateChangedNotification";
38. Step 6: Personalize
1.AppDelegate.m 파일의 -(void)sessionStateChanged:(FBSession *)session
함수안에 notification을 추가하여 세션변경때마다 호출한다.
- (void)sessionStateChanged:(FBSession *)session
state:(FBSessionState) state
error:(NSError *)error
{
switch (state) {
case FBSessionStateOpen: {
UIViewController *topViewController =
[self.navController topViewController];
if ([[topViewController modalViewController]
isKindOfClass:[FBLoginViewController class]]) {
[topViewController dismissModalViewControllerAnimated:YES];
}
}
break;
case FBSessionStateClosed:
case FBSessionStateClosedLoginFailed:
// Once the user has logged in, we want them to
// be looking at the root view.
[self.navController popToRootViewControllerAnimated:NO];
[FBSession.activeSession closeAndClearTokenInformation];
[self showLoginView];
break;
default:
break;
}
[[NSNotificationCenter defaultCenter] postNotificationName:FBSessionStateChangedNotification
object:session];
if (error) {
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:@"Error"
message:error.localizedDescription
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alertView show];
}
}
39. Step 6: Personalize
1.오류 수정
2012-05-18 04:04:11.620 Scrumptious[6548:f803] Unknown class
FBProfilePictureView in Interface Builder file.
add this as the first line in the app
delegate's
application:didFinishLaunchingWit
hOptions:method:
[FBProfilePictureView class];
40. Step 7: Show Friends
1.Facebook 친구들의 정보를 가져오기 위해서는 FBFriendPickerViewController
객체를 이용하면 된다.
2.FBFriendPickerViewController 을 사용하기 위해서는 initWithNibName:bundle:
함수 안에서 객체를 생성한다.
3.FBFriendPickerDelegate notifications 객체를 정의하기위한 델이게이트 메소드
를 셋팅한다.
4.마지막으로 loadData 함수를 호출하면 FBFriendPickerViewController에 친구
정보가 보여진다.
FBFriendPickerDelegate
friendPickerViewControllerSelectionDidChange:
FBFriendPickerViewController
selection property
41. Step 7: Show Friends
1.Set Up the User Interface
Add a Table View object
Style: Grouped;
Show Selection on Touch: NO;
Scrolling Enabled: NO;
• Create an outlet for the Table View object and call it
menuTableView.
• Connect the dataSource outlet to the File's Owner.
• Connect the delegate outlet to the File's Owner.
49. Step 7: Show Friends
1.Display Selected Friends
tableView:didSelectRowAtIndexPath: 함수에 다음 코드를 추가
한다.
self.friendPickerController.delegate = self;
Add the dealloc method
- (void)dealloc
{
_friendPickerController.delegate = nil;
}
51. Step 7: Show Friends
- (void)updateSelections
{
NSString* friendsSubtitle = @"Select friends";
int friendCount = self.selectedFriends.count;
if (friendCount > 2) {
// Just to mix things up, don't always show the first friend.
id<FBGraphUser> randomFriend =
[self.selectedFriends objectAtIndex:arc4random() % friendCount];
friendsSubtitle = [NSString stringWithFormat:@"%@ and %d others",
randomFriend.name,
friendCount - 1];
} else if (friendCount == 2) {
id<FBGraphUser> friend1 = [self.selectedFriends objectAtIndex:0];
id<FBGraphUser> friend2 = [self.selectedFriends objectAtIndex:1];
friendsSubtitle = [NSString stringWithFormat:@"%@ and %@",
friend1.name,
friend2.name];
} else if (friendCount == 1) {
id<FBGraphUser> friend = [self.selectedFriends objectAtIndex:0];
friendsSubtitle = friend.name;
}
[self updateCellIndex:2 withSubtitle:friendsSubtitle];
}
52. Step 7: Show Friends
Implement the FBFriendPickerDelegate method that will be notified of a friend selection
- (void)friendPickerViewControllerSelectionDidChange:
(FBFriendPickerViewController *)friendPicker
{
self.selectedFriends = friendPicker.selection;
[self updateSelections];
}
54. Step 8: Show Nearby Places
1.Facebook 친구들의 정보를 가져오기 위해서는 FBPlacePickerViewController
객체를 이용하면 된다.
2.FBFriendPickerViewController 을 사용하기 위해서는 initWithNibName:bundle:
함수 안에서 객체를 생성한다.
3.FBPlacePickerDelegate notifications 객체를 정의하기위한 델이게이트 메소드
를 셋팅한다.
4.마지막으로 loadData 함수를 호출하면 FBFriendPickerViewController에 친구
정보가 보여진다.
FBPlacePickerDelegate
placePickerViewControllerSelectionDidChange:
FBPlacePickerViewController
selection property
FBGraphPlace
55. Step 8: Show Nearby Places
1.Add the Core Location Framework
56. Step 8: Show Nearby Places
1.Get the User's Current Location
MyAppViewController.m 파일에 추가
@property (strong, nonatomic) CLLocationManager *locationManager;
@synthesize locationManager = _locationManager;
viewDidLoad 함수에 추가
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
self.locationManager.desiredAccuracy =
kCLLocationAccuracyNearestTenMeters;
self.locationManager.distanceFilter = 50;
[self.locationManager startUpdatingLocation];
57. Step 8: Show Nearby Places
1.Get the User's Current Location
MyAppViewController.m 파일에 추가
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
if (!oldLocation ||
(oldLocation.coordinate.latitude != newLocation.coordinate.latitude &&
oldLocation.coordinate.longitude != newLocation.coordinate.longitude)) {
// To-do, add code for triggering view controller update
NSLog(@"Got location: %f, %f",
newLocation.coordinate.latitude,
newLocation.coordinate.longitude);
}
}
- (void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error {
NSLog(@"%@", error);
}
58. Step 8: Show Nearby Places
1.Show the Nearby Place Selector
MyAppViewController.m 파일에 추가
@property (strong, nonatomic) FBPlacePickerViewController *placePickerController;
@synthesize placePickerController = _placePickerController;
tableView:didDeselectRowAtIndexPath 함수에 다음을 추가
case 1:
if (!self.placePickerController) {
self.placePickerController = [[FBPlacePickerViewController alloc]
initWithNibName:nil bundle:nil];
self.placePickerController.title = @"Select a restaurant";
}
self.placePickerController.locationCoordinate =
self.locationManager.location.coordinate;
self.placePickerController.radiusInMeters = 1000;
self.placePickerController.resultsLimit = 50;
self.placePickerController.searchText = @"restaurant";
[self.placePickerController loadData];
[self.navigationController pushViewController:self.placePickerController
animated:true];
break;
60. Step 8: Show Nearby Places
1.Display the Selected Place
tableView:didSelectRowAtIndexPath 메소드 수정
self.placePickerController.delegate = self;
MyAppviewController.m 에 다음을 추가
@property (strong, nonatomic) NSObject<FBGraphPlace>* selectedPlace;
@synthesize selectedPlace = _selectedPlace;
updateSelections 함수에 다음을 추가
[self updateCellIndex:1 withSubtitle:(self.selectedPlace ?
self.selectedPlace.name :
@"Select One")];
62. Step 9 : Publish to Feed
1.Facebook Timeline 의 구현을 Graph API를 사용하지 않고 대안으로
구현할수있는 Feed Dialog 방법을 설명한다.
2. FBRequestConnection 클래스를 이용한다.
3. startWithGraphPath:parameters:HTTPMethod:completionHandler:
함수를 사용한다.
4. USER_ID/feed 파라미터를 통하여 전달한다.
1: Set Up the Share View Trigger
63. Step 9 : Publish to Feed
1: Set Up the Share View Trigger
MyAppViewController.m 파일의 ViewDidLoad함수의 내용과 sessionStateChanged 함수의 내용을 변경
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
_loginButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[_loginButton setTitle:@"Publish" forState:UIControlStateNormal];
_loginButton.frame = CGRectMake(80, 350, 150, 50);
[_loginButton addTarget:self action:@selector(gofacebookpublish) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:_loginButton];
- (void)sessionStateChanged:(NSNotification*)notification {
if (FBSession.activeSession.isOpen) {
self.loginButton.hidden = NO;
} else {
self.loginButton.hidden = YES;
}
[self populateUserDetails];
}
65. Step 9 : Publish to Feed
3: Set Up the Share View
3-1. FBFeedViewcontroller 새로 생성
66. Step 9 : Publish to Feed
3: Set Up the Share View
3-2. FBFeedViewController.xib 파일에서 .m 파일로 드러그앤 코딩으로 Tool bar 구현한다.
67. Step 9 : Publish to Feed
3: Set Up the Share View
3-3. FBFeedViewController.xib 파일에서 .m 파일로 드러그앤 코딩으로 나머지 구현한다.
Message:
• Add a Text View object to the view below the toolbar. Stretch it out to take up most of the view's width.
• In the Connections Inspector, connect the delegate outlet to the File's Owner.
• Add an outlet to your view controller's implementation file so it's private. Name the outlet ''postMessageTextView''.
Image:
• Add an Image View object to the view below the ''Message'' text view, to the left of the main view.
• In the Attributes Inspector, set the View > Mode to Aspect Fit.
• In the Size Inspector, set the width to 80 and the height to 80.
• Add an outlet to your view controller's implementation file so it's private. Name the outlet ''postImageView''.
Name:
• In the Attributes Inspector, set the text color to a dark blue and the font to System Bold.
• Add an outlet to your view controller's implementation file so it's private. Name the outlet ''postNameLabel''.
Caption:
• Add a Label object to the view. Place it below the ''Name'' label.
• In the Attributes Inspector, set the text color to a dark gray and the make the font size smaller than the ''Name'' label. Set the Lines attribute to 0.
• Add an outlet to your view controller's implementation file so it's private. Name the outlet ''postCaptionLabel''.
Description:
• Add a Label object to the view. Place it below the ''Caption'' label.
• In the Attributes Inspector, set the font size to be smaller than the ''Name'' label font size. Set the Lines attribute to 0.
• Add an outlet to your view controller's implementation file so it's private. Name the outlet ''postDescriptionLabel''.
68. Step 9 : Publish to Feed
3: Set Up the Share View
3-3. FBFeedViewController.xib 파일에서 .m 파일로 드러그앤 코딩으로 나머지 구현한다.
69. Step 9 : Publish to Feed
3: Set Up the Share View
3-3. FBFeedViewController.m 코딩
text view에 미리 쓰여질 문자열 설정
text view에 미리 쓰여질 문자열 함수 구현
70. Step 9 : Publish to Feed
3: Set Up the Share View
3-3. FBFeedViewController.m 코딩 UITextViewDelegate 메스드 구현
71. Step 9 : Publish to Feed
3: Set Up the Share View
3-4. Configure the Display Data
initWithNibName:bundle 메소드에 추가
72. Step 9 : Publish to Feed
3: Set Up the Share View
3-4. Configure the Display Data
ViewDidLoad 메소드에 추가
73. Step 9 : Publish to Feed
3: Set Up the Share View
3-5. Load the Story Image
ViewDidLoad
ViewDidUnLoad
74. Step 9 : Publish to Feed
3: Set Up the Share View
3-5. Load the Story Image
NSURLConnection delegate methods
- (void)connection:(NSURLConnection*)connection
didReceiveData:(NSData*)data{
[self.imageData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
// Load the image
self.postImageView.image = [UIImage imageWithData:
[NSData dataWithData:self.imageData]];
self.imageConnection = nil;
self.imageData = nil;
}
- (void)connection:(NSURLConnection *)connection
didFailWithError:(NSError *)error{
self.imageConnection = nil;
self.imageData = nil;
}
75. Step 9 : Publish to Feed
3: Set Up the Share View
3-6. Configure the Cancel Action
- (IBAction)cancelButtonAction:(id)sender {
[[self presentingViewController]
dismissModalViewControllerAnimated:YES];
}
3-7. Present the Share View
FBFeedViewController.m 파일에 Import & 클릭함수 구현
-(void) gofacebookpublish
{
FBFeedViewController *viewController = [[FBFeedViewController alloc]
initWithNibName:@"FBFeedViewController"
bundle:nil];
[self presentViewController:viewController animated:YES completion:nil];
}