API等で送信先のURLを作成するのに件名にもしたメソッドを用いる場合があります。
defineでベースとなるURLを定義しておいて、相対パスを後から定義する以下の様な形。
#define apiBaseUrl @"https://api.hogehoge.com/1/fuga"
・・・
- (void) postHogehoge {
NSURL *url = [NSURL URLWithString:@"/foobarzoo" relativeToURL:[NSURL URLWithString:apiBaseUrl]];
// post!
}
このurlインスタンスを用いてpostしたけど・・・、あれ?404?
urlを出力してみると以下の様な出力がされます。
https://api.hogehoge.com/foobarzoo
え?/1/fugaは?
となります。
結論から言うと/の位置が誤っています。
#define apiBaseUrl @"https://api.hogehoge.com/1/fuga/"
・・・
- (void) postHogehoge {
NSURL *url = [NSURL URLWithString:@"foobarzoo" relativeToURL:[NSURL URLWithString:apiBaseUrl]];
// post!
}
この様に記述すると予想している動作をします。
誰かのお役に立てば。




コメント