iOS Objective-C 在自定义框架中显示 PNG 图像
Posted
技术标签:
【中文标题】iOS Objective-C 在自定义框架中显示 PNG 图像【英文标题】:iOS Objective-C Display PNG Image In Custom Framework 【发布时间】:2017-04-05 14:29:32 【问题描述】:我正在创建一个自定义框架。以前在框架中,我们会下载图像并使用它来显示在按钮中:
NSString *path = [NSString stringWithFormat: @"https://s3.amazonaws.com/assets/home.png"];
NSURL *url = [NSURL URLWithString:path];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *homeButton = [[UIImage alloc] initWithData:data];
self.rewardsCenterButton = [[UIBarButtonItem alloc] initWithImage:[homeButton imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]
style:UIBarButtonItemStylePlain
target:self
action: @selector(backToRewardsCenter:)];
但是,在审查此内容时,我们确定这不适合作为同步调用,因此我想将此 PNG 添加到框架本身。
我已经能够通过添加图像并确保它包含在复制捆绑资源构建阶段中来做到这一点。使用此设置,图像将添加到通用框架输出中:
但是,当我尝试在代码中添加它时,它似乎没有出现。另外,当我在项目中添加框架时,我没有看到包含的图像,只有标题:
这是我迄今为止尝试过的:
NSString* path = [NSString stringWithFormat:@"%@/TheoremReachSDK.framework/home.png", [[NSBundle mainBundle] bundlePath]];
UIImage *homeButton = [[UIImage alloc] initWithContentsOfFile:path];
还有:
NSBundle *bundle = [NSBundle bundleForClass:[TheoremReach class]];
NSString *path = [bundle pathForResource:@"home" ofType:@"png"];
UIImage *homeButton = [[UIImage alloc] initWithContentsOfFile:path];
还有:
UIImage *homeButton = [UIImage imageNamed:@"home.png"];
但这些都没有显示任何内容。知道我需要做什么才能显示图像吗?
【问题讨论】:
你为你的框架提供了什么包 ID? 不确定 - 我怎么看?我不确定我是否设置了... 查看你的 bundle 的 Info.plist 文件 在框架中设置为$(PRODUCT_BUNDLE_IDENTIFIER)
。
【参考方案1】:
我猜 NSBundle 没有通过以下调用找到框架:
[NSBundle bundleForClass:[TheoremReach class]]
尝试为您的框架提供一个明确的包 ID,例如:com.theoremreach.sdk
,清理您的项目,然后重新构建。
然后您可以使用这样的代码来获取并显示您的图像:
NSString *bundleIdentifier = @"com.theoremreach.sdk";
NSBundle *bundle = [NSBundle bundleWithIdentifier:bundleIdentifier];
if(bundle != nil)
NSString *path = [bundle pathForResource:@"home" ofType:@"png"];
UIImage *homeButtonImage = [[UIImage alloc] initWithContentsOfFile:path];
if(homeButtonImage != nil)
self.rewardsCenterButton = [[UIBarButtonItem alloc] initWithImage:[homeButtonImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]
style:UIBarButtonItemStylePlain
target:self
action: @selector(backToRewardsCenter:)];
else
NSLog(@"couldn't find home button image in bundle");
else
NSLog(@"could not find bundle with identifier %@", bundleIdentifier);
【讨论】:
这绝对看起来应该可以工作,但我不断看到它无法找到标识符为com.theoremreach.sdk
的包,尽管清理、构建和完全重新启动 Xcode :(
在您编译的应用程序中(即从您的应用程序项目的 Products 文件夹中)查看框架中的 Info.plist 文件,捆绑 ID 是否出现在那里?
似乎没有。但我也在cd
'ing 进入.app 之后使用了崇高的文本,并且大部分文件似乎已编码。我在这个 plist 中没有看到任何框架的东西
如果你双击 Info.plist 文件,它应该会在 Xcode 编辑器中打开。我目前的想法是,您认为您应用的捆绑 ID 并没有真正进入成品中嵌入的框架中。
所以它不是一个嵌入式框架,它只是一个框架——也许这就是问题所在?以上是关于iOS Objective-C 在自定义框架中显示 PNG 图像的主要内容,如果未能解决你的问题,请参考以下文章
iOS - WKURLSchemeHandler 未在自定义方案上调用