如何查找图像是否存在 - 解析

时间:2014-07-27 19:10:42

标签: ios parse-platform

我已成功从解析中检索图像(让我们说用户个人资料图片),并且我在ios应用程序中显示它。但是如果文件列中没有图像,那么我想显示存储在本地(不是解析)的默认图像,不成功。

我的简单问题是,如何检查是否有图像?下面是简单的代码;

PFFile *userImage = [object objectForKey:@"profilePic"]; __block UIImage *userProfilePic =[[UIImage alloc]init];

[userImage getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
    if (!error) {
        //this block will execute only if there is image
        if(data) {
            userProfilePic = [UIImage imageWithData:data];
            userPic.image=userProfilePic;
        }

        //this block is not at all executing. This block should execute when user doesn't have their profile uploaded
        if(!data) {
            UIImage *userProfileDefaultPic = [[UIImage alloc]init];
            userProfileDefaultPic=[UIImage imageNamed:@"defaultprofile.png"];
            userPic.image=userProfileDefaultPic;
        }
    }
}];
希望你能帮助我。提前致谢。

与Pradeep

2 个答案:

答案 0 :(得分:1)

终于找到了解决方案!

(!data)将不会执行,而是我们需要检查PFFile和存储PFFile的UIImage是否有图像,如下所示;

PFFile *userImage = [object objectForKey:@"profilePic"];
               __block UIImage *userProfilePic =[[UIImage alloc]init];
if(userImage && ![userProfilePic isEqual:[NSNull null]]) //This is important to check if the file if image is there or not and if not, then display default pic in else part

{
            [userImage getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
                if(!error)
                {

                        userProfilePic = [UIImage imageWithData:data];
                        userPic.image=userProfilePic;

                }
                 }];
            }
            else
            {
                userProfilePic =[UIImage imageNamed:@"defaultprofilepic.png"];
                userPic.image=userProfilePic;

            }

答案 1 :(得分:0)

您的代码已经这样做了。您只需要在主线程而不是后台线程上设置图像。

if(!data) { [dispatch_async(dispatch_get_main_queue(), ^{
        UIImage *userProfileDefaultPic = [[UIImage alloc]init];
        userProfileDefaultPic=[UIImage imageNamed:@"defaultprofile.png"];
        userPic.image=userProfileDefaultPic;
}}];