开发者

How can I properly manage my apps urls?

I have a very long list of urls that my app uses to retrieve data from the server. Currently, each url has their own constant, i.e.:

// constants.h
extern NSString * const profileUrl;

// constants.m
NSString * const profileUrl = @"http://api.site.com/profile";
.
.

It's not that big of a deal, but if I wanted to change the base url, I have to go in and replace all of them in each constant manually. I would like to keep with the DRY philosophy (Don'开发者_如何学Ct Repeat Yourself) if I can. Is something like what I'm doing below possible.

// constants.h
extern NSString * const baseUrl;
extern NSString * const profileUrl;

// constants.m
NSString * const baseUrl = @"http://api.site.com/";
NSString * const profileUrl = [NSString stringWithFormat:@"%@%@", baseUrl, @"profile"];

And if so, is there a standard way of handling your apps urls in an orderly fashion? What are some of the techniques that you use that make your life easier for this situation?


The absolute easiest way to do this is with macros:

#define FOOBAR_BASE @"http://www.example.com/"
#define FOOBAR_API_BAZ FOOBAR_BASE "baz"

You can even do this with NSString * const BarUrl = FOOBAR_BASE "baz";.

This is fine if you have a single "the server". It gets messier when you have multiple servers which you want to access from the same app without recompiling (dev/production?).

In one of our apps that does this, we just have a giant header file, which is a lot better than literal strings littered everywhere in the inherited codebase...


Just use:

NSDictionary *profileURLS = [NSDictionary dictionaryWithValues:[NSArray yourArrayOfProfileURLS] forKeys:[NSArray yourArrayOfCorrespondingProfiles]];

NSString *baseURL = @"baseURLHere";
NSString *newURL = [baseURL stringByAppeningString:[profileURLS valueForKey: profileName]];

I think this should work for what you are doing if I understand you correctly


I have a base url where I keep in MyAppDelegate:

In MyAppDelegate .h

extern NSString * const SERVER_URL;

And in MyAppDelegate.m

NSString *const SERVER_URL = @"http://111.11.11.1";

Then to access it just import MyAppDelegate.h

NSString *url = [SERVER_URL stringByAppendingString:@"/your_request"];


I keep them in a strings file. That way if the URL is different for a localized app, that's easy to accommodate with resource localization.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜