Swift2Jsonutf8字符串字符错误
Swift 2 Json utf8 string character error
我有工作 Json
文件和应用程序,但我有文本 encoding
问题。
我的Json
文件输出示例
{"status":"SUCCESS","data":[{"id":"21","title":"I'm working on project","description":"Lorem ipsum dolor sit er elit lamet, consectetaur cilliim adipisicin"}]}
Json
Parse Functions,我添加了解析一些你可以在
下看到的函数
func initArrayCategory(){
self.getResponseFromURL(self.getStringURLWithJSONFormatForUserAPI(URL_API_NEWS_CATEGORIES), withParams: nil, Success: { (operation, responseObject) -> () in
if let success = responseObject[API_PARAM_STATUS] as? String{
if success == "SUCCESS"{
if let data = responseObject[API_PARAM_DATA] as? NSMutableArray{
self.arrayCategory = data
}
}
self.Category.reloadData()
}
}, Failure: { (operation, error) -> () in
if error.localizedDescription == "The network connection was lost."{
self.initArrayCategory()
}
}, showLoader: true, hideLoader: true)
}
func postResponseFromURL(strURL: String, withParams dictParams:NSDictionary?, Success:(operation: AFHTTPRequestOperation!, responseObject:AnyObject!)->(),Failure:(operation: AFHTTPRequestOperation!, error:NSError!)->(),showLoader isShowDefaultLoader:Bool,showAnimated isShowLoaderAnimated:Bool, hideLoader isHideDefaultLoader:Bool)
{
let hudprogress = MBProgressHUD()
if isShowDefaultLoader{
MBProgressHUD.showHUDAddedTo(self.view, animated: true)
hudprogress.mode = MBProgressHUDModeDeterminate
hudprogress.labelText = "Loading"
}
let manager = AFHTTPRequestOperationManager()
manager.responseSerializer.acceptableContentTypes = NSSet(array: ["text/html", "application/json"]) as Set<NSObject>
manager.POST(strURL, parameters: dictParams, success: { (operation, responseObject) -> Void in
//println("RESPONSE DATA: " + responseObject.description)
if isHideDefaultLoader{
MBProgressHUD.hideAllHUDsForView(self.view, animated: true)
}
Success(operation: operation, responseObject: responseObject
)
}) { (operation, error) -> Void in
print("Response: \(operation.responseObject)")
print("Error: " + error.localizedDescription)
Failure(operation: operation, error: error)
hudprogress.hide(true)
}
}
let URL_API_HOST:String = "http://www.blabla.com/Items/"
func postResponseFromURL(strURL: String, withParams dictParams:NSDictionary?, Success:(operation: AFHTTPRequestOperation!, responseObject:AnyObject!)->(),Failure:(operation: AFHTTPRequestOperation!, error:NSError!)->(),showLoader isShowDefaultLoader:Bool, hideLoader isHideDefaultLoader:Bool)
{
self.postResponseFromURL(strURL, withParams: dictParams, Success: Success, Failure: Failure, showLoader: isShowDefaultLoader, showAnimated: true, hideLoader: isHideDefaultLoader)
}
func setObjectToUserDefaults(object:AnyObject, forKey strKey:String, writeToDisk isWrite:Bool )
{
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(object, forKey: strKey)
if isWrite{
defaults.synchronize()
}
}
func getStringURLWithJSONFormatForUserAPI(strAPI:String)->String{
return self.getStringURLForUserAPI(strAPI, withJSONFormat: true)
}
func getStringURLForUserAPI(strAPI:String, withJSONFormat isJSON:Bool)->String{
var strURL:String = self.getBaseURl()
strURL += strAPI
if isJSON
{
strURL = self.addJSONFormatInURL(strURL)
}
return strURL
}
func getBaseURl()->String{
return URL_API_HOST
}
func addJSONFormatInURL(strURL:String)->String{
return strURL + URL_API_FORMAT_JSON
}
我的视图控制器
class ViewController: UIViewController {
var detailTitle:String?
var detailDesc:String?
@IBOutlet weak var textim: UILabel!
@IBOutlet weak var textbig: UITextView!
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
textbig.text = detailDesc
textim.text = detailTitle
}
Mysql Table Mysql 文件
-- ----------------------------
-- Table structure for `App`
-- ----------------------------
DROP TABLE IF EXISTS `App`;
CREATE TABLE `App` (
`id` int(21) NOT NULL AUTO_INCREMENT,
`title` varchar(255) DEFAULT NULL,
`description` text,
`image` varchar(128) DEFAULT NULL,
`video` text,
`likes` int(21) DEFAULT NULL,
`visits` int(21) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=27 DEFAULT CHARSET=utf8;
Mysql 来自 Table
的真实价值
('21', 'I'm working on project', 'Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation. ', '7292754.jpg', '', '2', '26')
远程连接Php文件
$db_host="my host"; // your mysql database host name
$db_username="myusername"; // username
$db_pass="my past"; // password
$connnect=mysql_connect("$db_host","$db_username","$db_pass") or die("Databese Error, Please check your connection values !");
@mysql_select_db ("App"); // Select Your Database
@mysql_query("SET NAMES utf8");
@mysql_query("SET CHARACTER SET utf8");
@mysql_query("SET COLLATION_CONNECTION = 'utf8_general_ci'");
远程Php文件
header("Content-type: application/json; charset=utf-8");
include("connect.php");
$q = "Select * from App";
$r = mysql_query($q) or die(mysql_error());
if(mysql_num_rows($r) > 0) {
$arr = array();
while ($row = mysql_fetch_assoc($r))
{
$arr[] = $row;
}
echo json_encode(array('status'=>"SUCCESS",'data'=>$arr));
}
else {
echo json_encode(array('status'=>"FAIL"));
}
输出
textim.text = I'm working on project
必须是
textim.text = I'm working on project
json file coming title = I'm working on project
请帮帮我
TY
终于解决了,我觉得代码需要的人太多了!
谢谢@Eric D。我尝试了你的链接代码,我改变了一些东西,现在工作成功!
代码;
if let detailanother = detailTitle {
do {
let encodedData = detailanother.dataUsingEncoding(NSUTF8StringEncoding)!
let attributedOptions : [String: AnyObject] = [
NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: NSUTF8StringEncoding
]
let attributedString = try NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil)
self.textim.text = attributedString.string
} catch {
fatalError("Unhandled error: \(error)")
}
}
谢谢大家!
好的编码!
我有工作 Json
文件和应用程序,但我有文本 encoding
问题。
我的Json
文件输出示例
{"status":"SUCCESS","data":[{"id":"21","title":"I'm working on project","description":"Lorem ipsum dolor sit er elit lamet, consectetaur cilliim adipisicin"}]}
Json
Parse Functions,我添加了解析一些你可以在
func initArrayCategory(){
self.getResponseFromURL(self.getStringURLWithJSONFormatForUserAPI(URL_API_NEWS_CATEGORIES), withParams: nil, Success: { (operation, responseObject) -> () in
if let success = responseObject[API_PARAM_STATUS] as? String{
if success == "SUCCESS"{
if let data = responseObject[API_PARAM_DATA] as? NSMutableArray{
self.arrayCategory = data
}
}
self.Category.reloadData()
}
}, Failure: { (operation, error) -> () in
if error.localizedDescription == "The network connection was lost."{
self.initArrayCategory()
}
}, showLoader: true, hideLoader: true)
}
func postResponseFromURL(strURL: String, withParams dictParams:NSDictionary?, Success:(operation: AFHTTPRequestOperation!, responseObject:AnyObject!)->(),Failure:(operation: AFHTTPRequestOperation!, error:NSError!)->(),showLoader isShowDefaultLoader:Bool,showAnimated isShowLoaderAnimated:Bool, hideLoader isHideDefaultLoader:Bool)
{
let hudprogress = MBProgressHUD()
if isShowDefaultLoader{
MBProgressHUD.showHUDAddedTo(self.view, animated: true)
hudprogress.mode = MBProgressHUDModeDeterminate
hudprogress.labelText = "Loading"
}
let manager = AFHTTPRequestOperationManager()
manager.responseSerializer.acceptableContentTypes = NSSet(array: ["text/html", "application/json"]) as Set<NSObject>
manager.POST(strURL, parameters: dictParams, success: { (operation, responseObject) -> Void in
//println("RESPONSE DATA: " + responseObject.description)
if isHideDefaultLoader{
MBProgressHUD.hideAllHUDsForView(self.view, animated: true)
}
Success(operation: operation, responseObject: responseObject
)
}) { (operation, error) -> Void in
print("Response: \(operation.responseObject)")
print("Error: " + error.localizedDescription)
Failure(operation: operation, error: error)
hudprogress.hide(true)
}
}
let URL_API_HOST:String = "http://www.blabla.com/Items/"
func postResponseFromURL(strURL: String, withParams dictParams:NSDictionary?, Success:(operation: AFHTTPRequestOperation!, responseObject:AnyObject!)->(),Failure:(operation: AFHTTPRequestOperation!, error:NSError!)->(),showLoader isShowDefaultLoader:Bool, hideLoader isHideDefaultLoader:Bool)
{
self.postResponseFromURL(strURL, withParams: dictParams, Success: Success, Failure: Failure, showLoader: isShowDefaultLoader, showAnimated: true, hideLoader: isHideDefaultLoader)
}
func setObjectToUserDefaults(object:AnyObject, forKey strKey:String, writeToDisk isWrite:Bool )
{
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(object, forKey: strKey)
if isWrite{
defaults.synchronize()
}
}
func getStringURLWithJSONFormatForUserAPI(strAPI:String)->String{
return self.getStringURLForUserAPI(strAPI, withJSONFormat: true)
}
func getStringURLForUserAPI(strAPI:String, withJSONFormat isJSON:Bool)->String{
var strURL:String = self.getBaseURl()
strURL += strAPI
if isJSON
{
strURL = self.addJSONFormatInURL(strURL)
}
return strURL
}
func getBaseURl()->String{
return URL_API_HOST
}
func addJSONFormatInURL(strURL:String)->String{
return strURL + URL_API_FORMAT_JSON
}
我的视图控制器
class ViewController: UIViewController {
var detailTitle:String?
var detailDesc:String?
@IBOutlet weak var textim: UILabel!
@IBOutlet weak var textbig: UITextView!
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
textbig.text = detailDesc
textim.text = detailTitle
}
Mysql Table Mysql 文件
-- ----------------------------
-- Table structure for `App`
-- ----------------------------
DROP TABLE IF EXISTS `App`;
CREATE TABLE `App` (
`id` int(21) NOT NULL AUTO_INCREMENT,
`title` varchar(255) DEFAULT NULL,
`description` text,
`image` varchar(128) DEFAULT NULL,
`video` text,
`likes` int(21) DEFAULT NULL,
`visits` int(21) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=27 DEFAULT CHARSET=utf8;
Mysql 来自 Table
的真实价值('21', 'I'm working on project', 'Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation. ', '7292754.jpg', '', '2', '26')
远程连接Php文件
$db_host="my host"; // your mysql database host name
$db_username="myusername"; // username
$db_pass="my past"; // password
$connnect=mysql_connect("$db_host","$db_username","$db_pass") or die("Databese Error, Please check your connection values !");
@mysql_select_db ("App"); // Select Your Database
@mysql_query("SET NAMES utf8");
@mysql_query("SET CHARACTER SET utf8");
@mysql_query("SET COLLATION_CONNECTION = 'utf8_general_ci'");
远程Php文件
header("Content-type: application/json; charset=utf-8");
include("connect.php");
$q = "Select * from App";
$r = mysql_query($q) or die(mysql_error());
if(mysql_num_rows($r) > 0) {
$arr = array();
while ($row = mysql_fetch_assoc($r))
{
$arr[] = $row;
}
echo json_encode(array('status'=>"SUCCESS",'data'=>$arr));
}
else {
echo json_encode(array('status'=>"FAIL"));
}
输出
textim.text = I'm working on project
必须是
textim.text = I'm working on project
json file coming title = I'm working on project
请帮帮我
TY
终于解决了,我觉得代码需要的人太多了! 谢谢@Eric D。我尝试了你的链接代码,我改变了一些东西,现在工作成功!
代码;
if let detailanother = detailTitle {
do {
let encodedData = detailanother.dataUsingEncoding(NSUTF8StringEncoding)!
let attributedOptions : [String: AnyObject] = [
NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: NSUTF8StringEncoding
]
let attributedString = try NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil)
self.textim.text = attributedString.string
} catch {
fatalError("Unhandled error: \(error)")
}
}
谢谢大家! 好的编码!