Ошибка строкового символа Swift 2 Json utf8

У меня работает 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 Функции разбора, я добавил парсинг некоторых функций, которые вы можете увидеть под

    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 Real Value из таблицы

('21', 'I&#039;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&#039;m working on project

должно быть

textim.text = I'm working on project

json file coming title = I&#039;m working on project

пожалуйста, помогите мне

TY

0

Решение

Наконец я решил, я думаю, что кодов нужно слишком много людей!
Спасибо @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)")
}


}

Спасибо всем!
Хорошие кодировки!

0

Другие решения

Других решений пока нет …

По вопросам рекламы [email protected]