你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> IOS URL中文亂碼問題解決方案

IOS URL中文亂碼問題解決方案

編輯:IOS開發綜合

IOS 解決URL中文亂碼問題解決

在做一個HTTPS連接時, 要客戶端合成一段HTTPS地址

如果地址含中文的話程序會crash, 檢查發現原來是中文沒有轉碼的原因

在NSString庫裡面找到了下面兩個方法

- (NSString *)stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)encoding
- (NSString *)stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)encoding

試了下, 有效

NSString* string1 = @"https://www.cloudsafe.com/文件夾";

NSString* string2 = [string1 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString* string3 = [string2 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

NSString* string4 = [string2 stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString* string5 = [string3 stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

NSString* string6 = [string4 stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString* string7 = [string5 stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

輸出string1-7結果如下

string1:https://www.cloudsafe.com/文件夾

string2:https://www.cloudsafe.com/%E6%96%87%E4%BB%B6%E5%A4%B9
string3:https://www.cloudsafe.com/%25E6%2596%2587%25E4%25BB%25B6%25E5%25A4%25B9

string4:https://www.cloudsafe.com/文件夾
string5:https://www.cloudsafe.com/%E6%96%87%E4%BB%B6%E5%A4%B9

string6:https://www.cloudsafe.com/文件夾
string7:https://www.cloudsafe.com/文件夾

簡單說下我是如何使用的:

在合成URL後, 給整個String轉碼兩次

NSMutableString *address = [[NSMutableString stringWithString:SetNiChengStringWithoutUserNameAndNiCheng] mutableCopy];
  address = [[address stringByAppendingString:app.name] mutableCopy];
  address = [[address stringByAppendingString:@"/"] mutableCopy];
  address = [[address stringByAppendingString:_nameTextField.text] mutableCopy];
  address = [[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] mutableCopy];
  address = [[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] mutableCopy];

服務器端如何只是簡單存儲, 服務器接收數據後可以不用轉碼成中文

當客戶端請求這部分數據時, 由客戶端自己解碼就好了

獲取到字串後解碼一次就可以正常顯示為中文了:

 str = [str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 

感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!

  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved