Your SlideShare is downloading. ×
Facebook api
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Facebook api

2,738
views

Published on

Published in: Technology

0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
2,738
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
0
Comments
0
Likes
2
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • Transcript

    • 1. FaceBook OPEN API - Grahp Story- Develop S.O.Lab by 이상온
    • 2. Face Book API 3 TPYEWebSite 안에서 Face Book 연동 Api모바일 단말기에서 Face Book 연동앱개발facebook.com 내의 앱개발
    • 3. http://developers.facebook.com모바일 선택 = IOS/AndRoid
    • 4. 목차1. Facebook SDK install2. Run the sample3. Create Facebook App4. Start new X-code Project5. FACEBOOK Login & Authenticate6. Personalize7. Show Friends8. Show Nearby Places9. Publish to Feed
    • 5. Step 1: Facebook SDK install Facebook SDK install
    • 6. Step 1: Facebook SDK install
    • 7. Step 2: Run the sampleBasic 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.
    • 8. Step 3: Create Facebook App앱ID/API Key앱 시크릿코드
    • 9. Step 4: Start new X-code Project
    • 10. Step 4: Start new X-code Project
    • 11. Step 4: Start new X-code ProjectAdd the Facebook SDK for iOS Framework by dragging the FacebookSDK.frameworkfolderfrom the SDK installation folder into the Frameworks section of your Project Navigator.
    • 12. Step 4: Start new X-code ProjectAdd the Facebook SDK for iOS resource bundle by draggingtheFacebookSDKResources.bundle file from theFacebookSDK.framework/Resources folder into the Frameworks section of your Project Navigator.
    • 13. Step 4: Start new X-code ProjectAdd the -lsqlite3.0 SQL library to the list of build dependencies
    • 14. Step 4: Start new X-code ProjectFinally, you need to place the Facebook app ID in two places in your applicationsmain.plist file. Create a key called FacebookAppID with a string value, and addthe 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 & AuthenticateFBsession 객체 : login & Authorize manage• sessionOpenWithPermissions:completionHandler: 함수를 호출하여 퍼미션를 선언하고 세션인증을 받을 콜백 핸들러를 제공 한다.• Facebook App으로부터 받을 핸들러 구성• login or error 에대한 콜백핸들러 구현MyAppViewController : 로그인 후FBLoginViewController : 로그인 전
    • 17. Step 5: FACEBOOK Login & Authenticate New File > Object-c class > FBLoginViewControllerxib 파일에서 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 & Authenticate3.로그인뷰가 모달로 보여질것임으로,, MyAppViewController needs to be part of a UINavigationController. AppDelegate.h 파일에 new navigation controller 선언 @interface MyAppDelegate () @property (strong, nonatomic) UINavigationController* navController; @end4. AppDelegate.m 파일에 Synthesize this new property @synthesize navController = _navController;
    • 20. Step 5: FACEBOOK Login & Authenticate5. 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;
    • 21. Step 5: FACEBOOK Login & Authenticate7. application:didFinishLaunchingWithOptions: method, change this code: self.mainViewController = [[MyAppViewController alloc] initWithNibName:@"MyAppViewController_iPhone" bundle:nil]; self.navController = [[UINavigationController alloc] initWithRootViewController:self.mainViewController]; self.window.rootViewController = self.navController;8. AppDelegate.m 파일에 로그인뷰 보여줄 함수 구현 - (void)showLoginView { UIViewController *topViewController = [self.navController topViewController]; FBLoginViewController* loginViewController = [[FBLoginViewController alloc]initWithNibName:@"FBLoginViewController" bundle:nil]; [topViewController presentModalViewController:loginViewController animated:NO]; }
    • 22. Step 5: FACEBOOK Login & Authenticate9. 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 & Authenticate10. FBLoginViewController.xib attach an action to the login button & outlet to the activity indicator IN FBLoginViewController.m
    • 24. Step 5: FACEBOOK Login & Authenticate
    • 25. Step 5: FACEBOOK Login & Authenticate11. AppDelegate.m 파일에서 openSession 이라는 공용 메소드를 등록하고 login버튼을 클릭시 이함수를 호출한다.- (void)openSession{ [FBSession openActiveSessionWithPermissions:nil allowLoginUI:YEScompletionHandler: ^(FBSession *session, FBSessionState state, NSError *error) { [self sessionStateChanged:session state:state error:error]; }];}
    • 26. Step 5: FACEBOOK Login & Authenticate12. AppDelegate.m 파일에서 sessionStateChanged: state: error:이라는 메소드를등록 - (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: [self.navController popToRootViewControllerAnimated:NO]; [FBSession.activeSession closeAndClearTokenInformation]; [self showLoginView]; break; default: break; } if (error) { UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error" message:error.localizedDescription delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alertView show]; } }
    • 27. Step 5: FACEBOOK Login & Authenticate13. 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;
    • 28. Step 5: FACEBOOK Login & Authenticate15. FBLoginViewController.m 파일에 import #import "MyAppDelegate.h"16. FBLoginViewController.m - (IBAction)performLogin:(id)sender 함수 구현 - (IBAction)performLogin:(id)sender { [self.spinner startAnimating]; SCAppDelegate* appDelegate = [UIApplication sharedApplication].delegate; [appDelegate openSession]; }
    • 29. Step 5: FACEBOOK Login & Authenticate17. 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;
    • 30. Step 5: FACEBOOK Login & Authenticate 19. AppDelegate.m 파일의 showLoginView 함수를 수정- (void)showLoginView{ NSLog(@"showLoginView ~~함수 호출"); UIViewController *topViewController = [self.navController topViewController]; /* FBLoginViewController* loginViewController = [[FBLoginViewController alloc]initWithNibName:@"FBLoginViewController" bundle:nil]; [topViewController presentModalViewController:loginViewController animated:NO]; */ UIViewController *modalViewController = [topViewController modalViewController]; if (![modalViewController isKindOfClass:[FBLoginViewController class]]) { FBLoginViewController* loginViewController = [[FBLoginViewController alloc] initWithNibName:@"FBLoginViewController" bundle:nil]; [topViewController presentModalViewController:loginViewController animated:NO]; } else { FBLoginViewController* loginViewController = (FBLoginViewController*)modalViewController; [loginViewController loginFailed]; }}
    • 31. Step 5: FACEBOOK Login & Authenticate20. 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 & Authenticate22. 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 users profile picture and name when theyve authenticated.1) Facebook SDK FBRequest object2) activeSession on FBSession has been opened, or else provide an explicit FBSession instance to the FBRequestcalls.3) requestForMeWithSession that returns an FBRequestobject4) The user data will be a strongly typed FBGraphUser object5) Once youve constructed an FBRequest object, you can initiate the API call by invoking thestartWithCompletionHandler: method. View 추가후 class 를 FBProfilePictureView로 셋팅 XIB 객체선택후 ctl + 드레그 to 소스코드
    • 34. Step 6: Personalize
    • 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: Personalize1.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: Personalize1.오류 수정 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 appdelegatesapplication:didFinishLaunchingWithOptions:method: [FBProfilePictureView class];
    • 40. Step 7: Show Friends1.Facebook 친구들의 정보를 가져오기 위해서는 FBFriendPickerViewController 객체를 이용하면 된다.2.FBFriendPickerViewController 을 사용하기 위해서는 initWithNibName:bundle: 함수 안에서 객체를 생성한다.3.FBFriendPickerDelegate notifications 객체를 정의하기위한 델이게이트 메소드 를 셋팅한다.4.마지막으로 loadData 함수를 호출하면 FBFriendPickerViewController에 친구 정보가 보여진다. FBFriendPickerDelegate friendPickerViewControllerSelectionDidChange: FBFriendPickerViewController selection property
    • 41. Step 7: Show Friends1.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 Files Owner.• Connect the delegate outlet to the Files Owner.
    • 42. Step 7: Show Friends1.Set Up The Menu Display MyAppViewController.m 파일에 선언 @interface SCViewController () <UITableViewDataSource,UITableViewDelegate> MyAppViewController.m 파일에 TableView delegate 구현 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = (UITableViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; cell.selectionStyle = UITableViewCellSelectionStyleNone;
    • 43. Step 7: Show Friends cell.textLabel.font = [UIFont systemFontOfSize:16]; cell.textLabel.backgroundColor = [UIColor colorWithWhite:0 alpha:0]; cell.textLabel.lineBreakMode = UILineBreakModeTailTruncation; cell.textLabel.clipsToBounds = YES; cell.detailTextLabel.font = [UIFont systemFontOfSize:12]; cell.detailTextLabel.backgroundColor = [UIColor colorWithWhite:0 alpha:0]; cell.detailTextLabel.textColor = [UIColor colorWithRed:0.4 green:0.6 blue:0.8 alpha:1]; cell.detailTextLabel.lineBreakMode = UILineBreakModeTailTruncation; cell.detailTextLabel.clipsToBounds = YES;}switch (indexPath.row) { case 0: cell.textLabel.text = @"What are you eating?"; cell.detailTextLabel.text = @"Select one"; cell.imageView.image = [UIImage imageNamed:@"action-eating.png"]; break; case 1: cell.textLabel.text = @"Where are you?"; cell.detailTextLabel.text = @"Select one"; cell.imageView.image = [UIImage imageNamed:@"action-location.png"]; break;
    • 44. Step 7: Show Friendscase 2: cell.textLabel.text = @"With whom?"; cell.detailTextLabel.text = @"Select friends"; cell.imageView.image = [UIImage imageNamed:@"action-people.png"]; break; case 3: cell.textLabel.text = @"Got a picture?"; cell.detailTextLabel.text = @"Take one"; cell.imageView.image = [UIImage imageNamed:@"action-photo.png"]; break; default: break; } return cell;}
    • 45. Step 7: Show Friends- (NSInteger)tableView:(UITableView *)tableViewnumberOfRowsInSection:(NSInteger)section{ return 4;}- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView{ return 1;}- (void)tableView:(UITableView *)tableViewdidSelectRowAtIndexPath:(NSIndexPath *)indexPath{ // Do nothing for now}
    • 46. Step 7: Show Friends1.Show the Friend Selector MyAppViewController.m 파일에 추가 @property (strong, nonatomic) FBFriendPickerViewController *friendPickerController; @synthesize friendPickerController = _friendPickerController; ViewdidUnLoad 함수에 추가 self.friendPickerController = nil;
    • 47. Step 7: Show Friends tableView:didSelectRowAtIndexPath: 델리게이트 함수를 수정- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ switch (indexPath.row) { case 2: if (!self.friendPickerController) { self.friendPickerController = [[FBFriendPickerViewController alloc] initWithNibName:nil bundle:nil]; self.friendPickerController.title = @"Select friends"; } [self.friendPickerController loadData]; [self.navigationController pushViewController:self.friendPickerController animated:true]; }}
    • 48. Step 7: Show Friends
    • 49. Step 7: Show Friends1.Display Selected Friends tableView:didSelectRowAtIndexPath: 함수에 다음 코드를 추가 한다. self.friendPickerController.delegate = self; Add the dealloc method - (void)dealloc { _friendPickerController.delegate = nil; }
    • 50. Step 7: Show Friends1.Display Selected Friends @property (strong, nonatomic) NSArray* selectedFriends; @synthesize selectedFriends = _selectedFriends; - (void)updateCellIndex:(int)index withSubtitle:(NSString*)subtitle { UITableViewCell *cell = (UITableViewCell *)[self.menuTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]]; cell.detailTextLabel.text = subtitle; }
    • 51. Step 7: Show Friends- (void)updateSelections{ NSString* friendsSubtitle = @"Select friends"; int friendCount = self.selectedFriends.count; if (friendCount > 2) { // Just to mix things up, dont 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 FriendsImplement the FBFriendPickerDelegate method that will be notified of a friend selection - (void)friendPickerViewControllerSelectionDidChange: (FBFriendPickerViewController *)friendPicker { self.selectedFriends = friendPicker.selection; [self updateSelections]; }
    • 53. Step 7: Show Friends
    • 54. Step 8: Show Nearby Places1.Facebook 친구들의 정보를 가져오기 위해서는 FBPlacePickerViewController 객체를 이용하면 된다.2.FBFriendPickerViewController 을 사용하기 위해서는 initWithNibName:bundle: 함수 안에서 객체를 생성한다.3.FBPlacePickerDelegate notifications 객체를 정의하기위한 델이게이트 메소드 를 셋팅한다.4.마지막으로 loadData 함수를 호출하면 FBFriendPickerViewController에 친구 정보가 보여진다. FBPlacePickerDelegate placePickerViewControllerSelectionDidChange: FBPlacePickerViewController selection property FBGraphPlace
    • 55. Step 8: Show Nearby Places1.Add the Core Location Framework
    • 56. Step 8: Show Nearby Places1.Get the Users 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 Places1.Get the Users 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 Places1.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;
    • 59. Step 8: Show Nearby Places
    • 60. Step 8: Show Nearby Places1.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")];
    • 61. Step 8: Show Nearby PlacesFBPlacePickerDelegate 메소드 구현- (void)placePickerViewControllerSelectionDidChange:(FBPlacePickerViewController *)placePicker{ self.selectedPlace = placePicker.selection; [self updateSelections]; if (self.selectedPlace.count > 0) { [self.navigationController popViewControllerAnimated:true]; }}
    • 62. Step 9 : Publish to Feed1.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 TriggerMyAppViewController.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]; }
    • 64. Step 9 : Publish to Feed 2: Ask for Publish PermissionsAppDelegate.m 파일의 함수에서 퍼미션을 설정한다.- (void)openSession{ NSArray *permissions = [[NSArray alloc] initWithObjects: @"publish_actions", nil]; [FBSession openActiveSessionWithPermissions:permissions allowLoginUI:YES completionHandler: ^(FBSession *session, FBSessionState state, NSError *error) { [self sessionStateChanged:session state:state error:error]; }];}
    • 65. Step 9 : Publish to Feed 3: Set Up the Share View3-1. FBFeedViewcontroller 새로 생성
    • 66. Step 9 : Publish to Feed 3: Set Up the Share View3-2. FBFeedViewController.xib 파일에서 .m 파일로 드러그앤 코딩으로 Tool bar 구현한다.
    • 67. Step 9 : Publish to Feed 3: Set Up the Share View3-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 views width. • In the Connections Inspector, connect the delegate outlet to the Files Owner. • Add an outlet to your view controllers implementation file so its 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 controllers implementation file so its 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 controllers implementation file so its 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 controllers implementation file so its 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 controllers implementation file so its private. Name the outlet postDescriptionLabel.
    • 68. Step 9 : Publish to Feed3: Set Up the Share View 3-3. FBFeedViewController.xib 파일에서 .m 파일로 드러그앤 코딩으로 나머지 구현한다.
    • 69. Step 9 : Publish to Feed3: Set Up the Share View 3-3. FBFeedViewController.m 코딩text view에 미리 쓰여질 문자열 설정text view에 미리 쓰여질 문자열 함수 구현
    • 70. Step 9 : Publish to Feed3: Set Up the Share View 3-3. FBFeedViewController.m 코딩 UITextViewDelegate 메스드 구현
    • 71. Step 9 : Publish to Feed3: Set Up the Share View 3-4. Configure the Display Data initWithNibName:bundle 메소드에 추가
    • 72. Step 9 : Publish to Feed3: Set Up the Share View 3-4. Configure the Display Data ViewDidLoad 메소드에 추가
    • 73. Step 9 : Publish to Feed3: Set Up the Share View 3-5. Load the Story Image ViewDidLoad ViewDidUnLoad
    • 74. Step 9 : Publish to Feed3: 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 Feed3: 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]; }
    • 76. Step 9 : Publish to Feed4: Publish the Story FBFeedViewController.m 파일에 Import & 클릭함수 구현- (IBAction)shareButtonAction:(id)sender { if ([self.postMessageTextView isFirstResponder]) { [self.postMessageTextView resignFirstResponder]; } if (![self.postMessageTextView.text isEqualToString:kPlaceholderPostMessage] && ![self.postMessageTextView.text isEqualToString:@""]) { [self.postParams setObject:self.postMessageTextView.text forKey:@"message"]; } [FBRequestConnection startWithGraphPath:@"me/feed" parameters:self.postParams HTTPMethod:@"POST" completionHandler:^(FBRequestConnection *connection,id result,NSError *error) { NSString *alertText; if (error) { alertText = [NSString stringWithFormat:@"error: domain = %@, code = %d",error.domain, error.code]; } else { alertText = [NSString stringWithFormat:@"Posted action, id: %@",[result objectForKey:@"id"]]; } [[[UIAlertView alloc] initWithTitle:@"Result" message:alertText delegate:self cancelButtonTitle:@"OK!" otherButtonTitles:nil] show]; }];}
    • 77. Step 9 : Publish to Feed4: Publish the StoryFBFeedViewController.m 파일에 UIAlertView delegate 함수 구현