更改AFNetworking baseURL [英] changing AFNetworking baseURL

查看:403
本文介绍了更改AFNetworking baseURL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将AFNetworking与其示例中建议的单例模型一起使用.

I am using AFNetworking with the singleton model suggested in their example.

+ (SGStockRoomHTTPClient *)sharedClient
{
    static SGStockRoomHTTPClient *_sharedClient = nil;
    static dispatch_once_t oncePredicate;
    dispatch_once(&oncePredicate, ^{
        NSString *baseUrlString = [[NSUserDefaults standardUserDefaults] stringForKey:@"server_root_url_preference"];
        _sharedClient = [[self alloc] initWithBaseURL:[NSURL URLWithString:baseUrlString]];
    });

    return _sharedClient;
}

- (id)initWithBaseURL:(NSURL *)url {
    self = [super initWithBaseURL:url];
    if (!self) {
        return nil;
    }
    [self registerHTTPOperationClass:[AFJSONRequestOperation class]];
    [self setDefaultHeader:@"Accept" value:@"text/html"];
return self;
}

初始化是使用从用户默认值中获取的baseURL完成的.

Initialization is done with a baseURL taken from the user defaults.

我的问题是baseURL属性是只读的.如果用户进入设置并更改了baseURL用户默认设置,该如何在客户端中对其进行更改?

My problem is that the baseURL property is read-only. If the user goes to settings and changes the baseURL user default, how can I change it in my client?

我需要更改baseURL的另一种类似情况是API,该API需要多次调用和逻辑操作才能确定正确的baseURL.而且,在应用运行时,基本URL仍然可以更改(例如,用户更改网络环境,需要通过外部代理服务器将本地连接更改为3G连接.)

Another similar case I have with a need to change the baseURL is an API which requires multiple calls and logic to determine to the right baseURL. And the base url can still change while the app is running (e.g. user changes networking environment requiring a change from local connection to 3G connection via external proxy server.).

我明白了为什么baseURL属性是只读的:诸如networkReachabilityStatus之类的东西在后台运行并与该设置相关联.也就是说,拥有一个setBaseURL方法似乎很容易,该方法可以停止监视,更改值,然后再次开始监视...

I see why the baseURL property is read-only: there are things like networkReachabilityStatus that run in the background and are tied to that setting. This said, it seems fairly easy to have a setBaseURL method that stops monitoring, changes the value, then starts monitoring again...

我想我的设计不合适,在这种情况下我应该放弃单例并在每次baseURL更改时重新创建客户端吗?

I guess my design is not right, should I give-up the singleton in this case and re-create the client each time the baseURL should change?

推荐答案

AFHTTPClient设计为可使用单个基本URL.这就是为什么它是只读的.

The class AFHTTPClient is designed to work with a single base URL. This is why it is readonly.

如果您有多个基本URL,以下是一些解决方案:

Here are some solutions if you have more than one base URL:

    AFHTTPClient子类中的
  • 会覆盖属性限定符.将其放在@interface内:@property (readwrite, nonatomic, retain) NSURL *baseURL;

完全不使用AFHTTPClient

创建AFHTTPClient

创建HTTP操作时,可以覆盖baseURL.只需在路径中设置完整的URL,而不是相对路径即可.

When you create HTTP operations you can override the baseURL. Just set the full URL in the path instead of a relative path.

这篇关于更改AFNetworking baseURL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆