hachinoBlog

hachinobuのエンジニアライフ

ローカルファイルからNSURLRequestを生成してNSURLConnectionで接続する方法

外部のサーバにあるxmlファイルじゃなくて自分のプロジェクト内にxmlファイルを置いて
それを読み込んでリクエストを作成してNSURLConnectionでNSDateを取得したかったんだけど

NSString *filePath = [[NSBundle mainBundle] pathForResource:[ファイル名] ofType:@"xml"];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:filePath]];

NSError *error = nil;
NSURLResponse *response = nil;

NSData *xmlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

これだとxmlDataにはnullが代入されていた。
原因としては

[NSURL URLWithString:filePath]

じゃなく

[NSURL fileURLWithPath:filePath]

でファイルパスを取ってやらなければいけなかった。
ローカルファイルを読む場合はこっちですね。。