Search code examples
phpiosjsonswift2utf8-decode

Swift 2 Json utf8 string character error


I have working Json file and app, but i have text encoding problem.

My Json file output example

{"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, I added parsing some functions you can see under

    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
    }

My view controller

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 File

-- ----------------------------
--  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 from Table

('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')

Remote connect Php File

$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'");

Remote Php File

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"));
        }       

Output

textim.text =  I&#039;m working on project

must be

textim.text = I'm working on project

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

Please help me

TY


Solution

  • Finally I Resolved, I think that codes need too many people ! Thanks @Eric D. I try your linked codes and i changed somethings and now working success !

    Codes ;

    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)")
                }
    
    
        }
    

    Thanks for everyone ! Good codings !