FBProfilePictureView - 将UIImage保存到UserDefaults

时间:2014-07-21 15:02:41

标签: xcode facebook uiimage profile facebook-ios-sdk

如何从FBProfilePictureView中取出UIImage?我找不到能够正确解释的帖子,请查看下面的答案,随时编辑它!

1 个答案:

答案 0 :(得分:1)

所以这是我前几天在这里寻找的一个问题,但找不到正确的答案,所以我认为我会回答社区的问题。这是:

您需要设置一个登录按钮,其中包含:

- (void)fbMethodLoggedInWithFbUser:(id<FBGraphUser>)user

委托方法已经有效。

我们将在loggin = Success之后使用带有“Continue”按钮的登录屏幕来捕获UIImage,因此在故事板上添加一个“Continue”按钮(用于在登录后推送到下一个屏幕)以及一个View with “FBProfilePictureView”类,它链接到头文件,如下所示:

@property (strong, nonatomic) IBOutlet FBProfilePictureView *userProfilePic;

然后在.m文件中合成它,如下所示:

@synthesise userProfilePic;

然后在ViewDidLoad中设置Delegate,如下所示:

- (void)viewDidLoad {
    [userProfilePic setDelegate:self];
}

现在我们要在.m文件中的任何位置添加此行(确保它没有嵌套在函数内!)

id<FBGraphUser>cachedUser;

在前面提到的Delegate方法(fbMethodLoggedInWithFbUser)中,我们将新创建的id标记设置为等于委托方法的passthrough值,如下所示:

- (void)fbMethodLoggedInWithFbUser:(id<FBGraphUser>)user {
    cachedUser = user;

    // other login methods go here

}

现在您的用户已登录,我们拥有“ID”缓存。用户登录后使用“继续”按钮最有效的原因是,我要发布的代码将获取Facebook用作临时图像的默认空白个人资料图片图像,直到用户个人资料图片加载为止。因此,为了确保不会发生这种情况,首先添加这两种方法,然后我们将第一个链接到“继续”按钮操作:

- (void)getProfilePictureWithFbUser:(id<FBGraphUser>)user {
    userProfilePic.profileID = user.id;
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.4f];
    [userProfilePic setAlpha:1];
    [UIView commitAnimations];

    // -----------------------
    // CATCH PROFILE PICTURE::

    for (id obj in userProfilePic.subviews) {
        if ([obj isKindOfClass:[UIImageView class]]) {
            UIImageView *tempImageView = obj;
            UIImage *tempImage = tempImageView.image;
            [self saveImageToUDWithImage:tempImage];
        }
    }

}

此方法是将捕获的UIImage从'userProfilePic'视图保存到UserDefaults:

- (void)saveImageWithUDWithImage:(UIImage *)tempImage {

    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    [ud setObject:UIImagePNGRepresentation(tempImage) forKey:@"userProfilePicture"];
    [ud synchronize];

}

现在设置你的继续按钮:

- (IBAction)continueButtonActionAfterLogin:(id)sender {

    // First we capture the user profile pic
    // with the cached id we got earlier after
    // login:

    [self captureProfilePicWithFBUser:cachedUser];

    // You can execute model pushes here, etc...

}

然后,稍后从UserDefaults读取UIImage,请使用以下方法:

- (UIImage *)loadProfilePicFromUserDefaults {
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    NSData *imageData = [[NSUserDefaults standardUserDefaults] objectForKey:@"userProfilePicture"];
    UIImage *image = [UIImage imageWithData:imageData];
    return image;
}

这可以在任何其他要显示用户个人资料图片的类中调用:

- (void)viewDidLoad {

    [myWantingToBeProfilePicture setImage:[self loadProfilePicFromUserDefaults];

}

很抱歉代码全面到位,但我已经用一种让我清楚的方式对其进行了解释,我希望其他人也清楚这一点!随意编辑并使其更好!

@Declanland

相关问题