Я новичок в разработке iOS. Мне нужно интегрировать вход в Facebook в моем приложении iOS, так как пользователь регистрируется в нем, получает всю информацию и переводит ее на главный экран. Я сделал это через последнюю версию SDK на Facebook, но я хочу, чтобы это было сделано через социальные рамки. Я прошел через множество онлайн-материалов, а также нашел примеры, где они размещают (размещают) контент на странице Facebook (Стена) через социальную структуру, но не точно в Facebook. Кто-нибудь, пожалуйста, помогите, сообщите мне, если Facebook-вход возможен через социальную структуру, или я должен придерживаться SDK. Спасибо в Advance
Вход в Facebook через социальную инфраструктуру в ios
Ответ 1
Импорт социальных и вспомогательных фреймов
поместите этот код в ваш .m файл
-(void)facebook
{
self.accountStore = [[ACAccountStore alloc]init];
ACAccountType *FBaccountType= [self.accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
NSString *key = @"451805654875339";
NSDictionary *dictFB = [NSDictionary dictionaryWithObjectsAndKeys:key,ACFacebookAppIdKey,@[@"email"],ACFacebookPermissionsKey, nil];
[self.accountStore requestAccessToAccountsWithType:FBaccountType options:dictFB completion:
^(BOOL granted, NSError *e) {
if (granted)
{
NSArray *accounts = [self.accountStore accountsWithAccountType:FBaccountType];
//it will always be the last object with single sign on
self.facebookAccount = [accounts lastObject];
ACAccountCredential *facebookCredential = [self.facebookAccount credential];
NSString *accessToken = [facebookCredential oauthToken];
NSLog(@"Facebook Access Token: %@", accessToken);
NSLog(@"facebook account =%@",self.facebookAccount);
[self get];
[self getFBFriends];
isFacebookAvailable = 1;
} else
{
//Fail gracefully...
NSLog(@"error getting permission yupeeeeeee %@",e);
sleep(10);
NSLog(@"awake from sleep");
isFacebookAvailable = 0;
}
}];
}
-(void)checkfacebookstatus
{
if (isFacebookAvailable == 0)
{
[self checkFacebook];
isFacebookAvailable = 1;
}
else
{
printf("Get out from our game");
}
}
-(void)get
{
NSURL *requestURL = [NSURL URLWithString:@"https://graph.facebook.com/me"];
SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeFacebook requestMethod:SLRequestMethodGET URL:requestURL parameters:nil];
request.account = self.facebookAccount;
[request performRequestWithHandler:^(NSData *data, NSHTTPURLResponse *response, NSError *error) {
if(!error)
{
NSDictionary *list =[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(@"Dictionary contains: %@", list );
self.globalmailID = [NSString stringWithFormat:@"%@",[list objectForKey:@"email"]];
NSLog(@"global mail ID : %@",globalmailID);
fbname = [NSString stringWithFormat:@"%@",[list objectForKey:@"name"]];
NSLog(@"faceboooookkkk name %@",fbname);
if([list objectForKey:@"error"]!=nil)
{
[self attemptRenewCredentials];
}
dispatch_async(dispatch_get_main_queue(),^{
});
}
else
{
//handle error gracefully
NSLog(@"error from get%@",error);
//attempt to revalidate credentials
}
}];
self.accountStore = [[ACAccountStore alloc]init];
ACAccountType *FBaccountType= [self.accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
NSString *key = @"451805654875339";
NSDictionary *dictFB = [NSDictionary dictionaryWithObjectsAndKeys:key,ACFacebookAppIdKey,@[@"friends_videos"],ACFacebookPermissionsKey, nil];
[self.accountStore requestAccessToAccountsWithType:FBaccountType options:dictFB completion:
^(BOOL granted, NSError *e) {}];
}
-(void)accountChanged:(NSNotification *)notification
{
[self attemptRenewCredentials];
}
-(void)attemptRenewCredentials
{
[self.accountStore renewCredentialsForAccount:(ACAccount *)self.facebookAccount completion:^(ACAccountCredentialRenewResult renewResult, NSError *error){
if(!error)
{
switch (renewResult) {
case ACAccountCredentialRenewResultRenewed:
NSLog(@"Good to go");
[self get];
break;
case ACAccountCredentialRenewResultRejected:
NSLog(@"User declined permission");
break;
case ACAccountCredentialRenewResultFailed:
NSLog(@"non-user-initiated cancel, you may attempt to retry");
break;
default:
break;
}
}
else{
//handle error gracefully
NSLog(@"error from renew credentials%@",error);
}
}];
}
Также зарегистрировался в вашем родном приложении Facebook на вашем устройстве/симуляторе
Ответ 2
Swift 3 Версия решения @reena
@IBAction func loginButtonPressed(_ sender: UIButton) {
var facebookAccount: ACAccount?
let options:[String : Any] = [ACFacebookAppIdKey: "YOUR_FACEBOOK_API_KEY", ACFacebookPermissionsKey: ["email"],ACFacebookAudienceKey:ACFacebookAudienceFriends]
let accountStore = ACAccountStore()
let facebookAccountType = accountStore.accountType(withAccountTypeIdentifier: ACAccountTypeIdentifierFacebook)
accountStore.requestAccessToAccounts(with: facebookAccountType, options: options) { (granted:Bool, error:Error?) in
if granted{
let accounts = accountStore.accounts(with: facebookAccountType)
facebookAccount = accounts?.last as? ACAccount
let dict:NSDictionary = facebookAccount!.dictionaryWithValues(forKeys: ["properties"]) as NSDictionary
let properties:NSDictionary = dict["properties"] as! NSDictionary
print("facebook Response is-->:%@",properties)
}
else {
if let err = error as? NSError, err.code == Int(ACErrorAccountNotFound.rawValue) {
DispatchQueue.main.async {
self.displayAlert("There is no Facebook accounts configured. you can add or created a Facebook account in your settings.")
}
} else {
DispatchQueue.main.async {
self.displayAlert("Permission not granted For Your Application")
}
}
}
}
}
Ответ 3
Facebook, используя учетные записи и социальные рамки (быстро)
var facebookAccount: ACAccount?
let options: [NSObject : AnyObject] = [ACFacebookAppIdKey: "YOUR_FACEBOOK_API_KEY", ACFacebookPermissionsKey: ["publish_stream","publish_actions"],ACFacebookAudienceKey:ACFacebookAudienceFriends]
let accountStore = ACAccountStore()
let facebookAccountType = accountStore.accountTypeWithAccountTypeIdentifier(ACAccountTypeIdentifierFacebook)
accountStore.requestAccessToAccountsWithType(facebookAccountType, options: options) { (granted, error) -> Void in
if granted
{
let accounts = accountStore.accountsWithAccountType(facebookAccountType)
self.facebookAccount = accounts.last as? ACAccount
let accountsArray=accountStore.accountsWithAccountType(facebookAccountType) as NSArray
self.facebookAccount=accountsArray.lastObject as? ACAccount
var dict:NSDictionary
dict=NSDictionary()
dict=self.facebookAccount!.dictionaryWithValuesForKeys(["properties"])
let properties:NSDictionary=dict["properties"] as! NSDictionary
print("facebook Response is-->:%@",properties)
}
else
{
if error.code == Int(ACErrorAccountNotFound.rawValue) {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.displayAlert("There is no Facebook accounts configured. you can add or created a Facebook account in your settings.")
})
} else {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.displayAlert("Permission not granted For Your Application")
})
}
}
}