2016-07-04 26 views
2

我正在使用AFNetworking的iOS,我想發送請求與查詢參數有一個日期時間作爲值。想要的行爲應該是:AFNetworking URL參數編碼的日期時間與+和:標誌

Original: 2016-07-04T14:30:21+0200 
Encoded: 2016-07-04T14%3A30%3A21%2B0200 
Example: .../?datetime=2016-07-04T14%3A30%3A21%2B0200 

AFNetworking確實本身字符串編碼不包含特殊字符,如+/& :,還有一些人(Wikipedia: Percent-encoding),因爲它們是保留這是罰款。 所以我必須編碼我的日期時間的值另一種方式來逃避加號和冒號。但是,當我在AFNetworking之前手動編碼值時,它顯然會跳出%兩次。所以它把每個%

2016-07-04T14%253A30%253A21%252B0200 

我想AFNetworking使用編碼%的查詢與像允許的字符一個%25

query.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLPathAllowedCharacterSet()) 

我沒有找到一個解決方案來改變或禁用編碼由AFNetworking完全手動完成。你有什麼建議嗎?

回答

2

經過多一點研究後,我發現了一個注入我想要的編碼的地方。這是它沒有工作方式:

編碼不工作

初始化的requestOperationManager

self.requestOperationManager = [[AFHTTPRequestOperationManager alloc] init]; 
self.requestOperationManager.requestSerializer = [AFJSONRequestSerializer serializer]; 

使用requestOperationManager來初始化操作

NSURLRequest *request = [NSURLRequest alloc] initWithURL:url]; // The problem is here 
AFHTTPRequestOperation *operation = [self.requestOperationManager HTTPRequestOperationWithRequest:urlRequest success:^(AFHTTPRequestOperation *operation, id responseObject) { 
    // Success 
} failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
    // Failure 
}]; 
[self.requestOperationManager.operationQueue addOperation:operation]; 
[operation start]; 

方式有更多的控制

AFHTTPRequestSerializer也可以創建請求,您可以使用自己的序列化。

初始化的requestOperationManager並添加查詢字符串序列化區塊:

self.requestOperationManager = [[AFHTTPRequestOperationManager alloc] init]; 
self.requestOperationManager.requestSerializer = [AFJSONRequestSerializer serializer]; 
[self.requestOperationManager.requestSerializer setQueryStringSerializationWithBlock:^NSString * _Nonnull(NSURLRequest * _Nonnull request, id _Nonnull parameters, NSError * _Nullable __autoreleasing * _Nullable error) { 
    if ([parameters isKindOfClass:[NSString class]]) { 
     NSString *yourEncodedParameterString = // What every you want to do with it. 
     return yourEncodedParameterString; 
    } 
    return parameters; 
}]; 

現在改變你如何創建NSURLRequest

NSString *method = @"GET"; 
NSString *urlStringWithoutQuery = @"http://example.com/"; 
NSString *query = @"datetime=2016-07-06T12:15:42+0200" 
NSMutableURLRequest *urlRequest = [self.requestOperationManager.requestSerializer requestWithMethod:method URLString:urlStringWithoutQuery parameters:query error:nil]; 

這是重要,你拆你的網址。使用url而不用查詢URLString參數,只查詢parameters參數。通過使用requestWithMethod:URLString:parameters:error它將調用上面提供的查詢字符串序列化塊,並根據需要對參數進行編碼。

AFHTTPRequestOperation *operation = [self.requestOperationManager HTTPRequestOperationWithRequest:urlRequest success:^(AFHTTPRequestOperation *operation, id responseObject) { 
    // Success 
} failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
    // Failure 
}]; 
[self.requestOperationManager.operationQueue addOperation:operation]; 
[operation start];