หลายคนที่ทำแอพแล้วต้องการแชร์รูปลง Facebook คงต้องปวดหัวน่าดูกับโค๊ดที่ยุ่งยาก แต่พอมี iOS 7 มันเป็นอะไรที่ง่ายมากเลย
จากที่ Apple ได้ปล่อย iOS 7 แล้วใน Setting สังเกตุดีๆว่ามันจะฝันส่วนที่เป็น Social Network เช่น Twitter, Facebook มาให้ โดยให้ผู้ใช้ใส่ Account เข้าไปได้เลย มันก็เลยส่งผลให้ผู้พัฒนาแอพสามารถเรียกใช้คุณสมบัตินี้ได้โดยง่าย โดยไม่ต้องยุ่งกับ SDK ของ facebook หรือ SDK ของ twitter อีก วิธีการโพสหรือแชร์รูปลง Facebook มีดังนี้
1. เพิ่มเฟรมเวิร์ค Social.Framework โดยไปที่โปรเจค > Build Phases > Link binary with binaries แล้วกด + เลือกเฟรมเวิร์คชื่อ Social.framework
1 |
Social.framework |
2. อิมพอร์ต Social.h ในไฟล์ xxx.h หน้าที่เราจะแชร์
1 |
#import <Social/Social.h> |
3. ประกาศ property ชื่อ slComposeViewController ในไฟล์ xxx.h หน้าที่เราจะแชร์
1 |
@property (strong, nonatomic) SLComposeViewController *slComposeViewController; |
4. ในไฟล์ xxx.m สมมติว่ามีเมธอด shareWithFacebook ในคำสั่งดังนี้
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
-(void)shareWithFacebook{ NSData *imageData = UIImageJPEGRepresentation(@"ชื่อรูป", 1.f); NSString *tempString = [NSString stringWithFormat:@"ข้อความที่ต้องการแชร์"]; if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook]) { self.slComposeViewController = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook]; [self.slComposeViewController addImage:[UIImage imageWithData:imageData]]; [self.slComposeViewController setInitialText:tempString]; [self presentViewController:self.slComposeViewController animated:YES completion:NULL]; }else{ UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"No account found." message:@"Configure a Facebook account in setting" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil]; [alert show]; } } |
เรียบร้อย…:)