0

メイン バンドル内のファイルの内容を含む NSData オブジェクトを作成しようとしています。

NSString *chordPath = [[NSBundle mainBundle] pathForResource:chordName ofType:@"png"];

NSURL *chordURL = [NSURL URLWithString:[chordPath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSData *chordImageData = [NSData dataWithContentsOfURL:chordURL];
UIImage *chordImage = [UIImage imageWithData:chordImageData];

使用する前stringByAddingPercentEscapesUsingEncodingは nil URL を取得していたので、先に進み、文字列を再エンコードして修正しました。これで有効な URL を取得できましたが、chordImageDataオブジェクトは nil です。このファイルは間違いなくメイン バンドルに含まれているため (最初に URL を取得できたため)、何が問題なのか疑問に思っています。

編集:

これを実行する:

NSData *chordImageData = [NSData dataWithContentsOfURL:chordURL options:NSDataReadingMapped error:&dataCreationError];

エラーのためにこれを取得します:

po dataCreationError
Error Domain=NSCocoaErrorDomain Code=256 "The operation couldn’t be completed. (Cocoa error 256.)" UserInfo=0x7530a00

Google を見回すと、URL がまだ正しくエンコードされていないようです。エンコーディングが有効であることを確認するための追加の手順を知っている人はいますか?

4

2 に答える 2

1

パーセントエスケープを行う必要はありません。問題が発生している理由はURLWithString:、「ファイル以外の」URL用のURLを使用しているためです。

+fileURLWithPath:ファイルベースのURLには次のものを使用する必要があります。

NSString *chordPath = [[NSBundle mainBundle] pathForResource:chordName ofType:@"png"];

NSURL *chordURL = [NSURL fileURLWithPath:chordPath];
NSData *chordImageData = [NSData dataWithContentsOfURL:chordURL];
UIImage *chordImage = [UIImage imageWithData:chordImageData];
于 2012-10-08T16:57:35.087 に答える
1

次のような fileURLWithPath: を使用してみてください。

NSString *chordPath = [[NSBundle mainBundle] pathForResource:chordName ofType:@"png"];

NSURL *chordURL = [NSURL fileURLWithPath: chordPath];
NSData *chordImageData = [NSData dataWithContentsOfURL:chordURL];
UIImage *chordImage = [UIImage imageWithData:chordImageData];
于 2012-10-08T16:56:31.613 に答える