-2

I have an array of dictionnaries: [[String:String]]. Every dictionnary countain a string parameter (text) in french.

When I put this array in a dictionnary: [String:AnyObject], accents in the string text parameter are converted in their unicode.

For example é become \U00e9

I know my string is ok but it's wrong in the server. When I send to the server this text : "Le kit de réparation de portable est toulousain", he receive "Le kit de r\U00e9paration de portable est toulousain". I know the server is good and the problem doesn't come from here.

I believe the problem come from the type AnyObject of my dictionnary args but I don't how to solve.

Here's my code :

var args: [String:AnyObject] = [
        "action":"share",
        "id": NSNumber(longLong: id)
    ]
    var shareOn = [[String:String]]()
    if let sharers = User.currentUser?.sharers {
        for (index, object) in enumerate(sharers) {
            if object.enabled == true {
                var sharerContent: [String:String] = ["sharerId": object.sharerId, "cnxId": String(object.cnxId)]
                if object.shareAsImageEnable == true {
                    sharerContent["shareAsImage"] = "true"
                }
                if object.mustSpecifyShareText == true {
                    var text : String! = (title != nil) ? title : ""
                    if object.sharerId.lowercaseString.rangeOfString("twitter") != nil {
                        let maxLength = 140 - 27 // Twitter limit - max URL long
                        if text.length > maxLength {
                            let index: String.Index = advance(text.startIndex, maxLength-3)
                            text = text.substringToIndex(index) + "... http://ppo.az/..."
                        } else {
                            text = text + " http://ppo.az/..."
                        }
                    }
                    sharerContent["text"] = text
                }
                shareOn.append(sharerContent)
            }
        }
    }

    println(shareOn)

    args["shareOn"] = shareOn

    println(args)

And the results of println:

println(shareOn) => accent OK =>

[[sharerId: facebook, cnxId: 4230821, shareAsImage: true, text: Le kit de réparation de portable est toulousain]]

println(args) => accent NOT OK =>

[action: share, id: 4049850929, shareOn: ( { cnxId = 4150811; shareAsImage = true; sharerId = facebook; text = "Le kit de r\U00e9paration de portable est toulousain"; } )]

And my Router and my function makeRequest :

import UIKit
import Alamofire
import OAuthSwift

enum Router: URLRequestConvertible {

static let baseURLString: String! = Global.kClientAPIURL
static var oauthClient: OAuthSwiftClient!

case Login([String: AnyObject])
case LoginSocial([String: AnyObject])
case Profil([String: AnyObject])
case GetCompilation([String: AnyObject])
case GetSavedSearch([String: AnyObject])
case sharePost([String: AnyObject])


var URLRequest: NSURLRequest {
    let (method: Alamofire.Method, path: String, parameters : [String: AnyObject]?) = {
        switch self {
        case .Login(let params):
            return (.POST, "api/1/login", params)
        case .LoginSocial(let params):
            return (.POST, "api/1/login-with-social-account", params)
        case .Profil(let params):
            return (.GET, "api/1/profile", params)
        case .GetCompilation(let params):
            return (.GET, "api/1/compilation", params)
        case .GetSavedSearch(let params):
            return (.GET, "api/1/search", params)
        case .sharePost(let params):
            return (.POST, "api/1/post", params)
        }
    }()

    let URL = NSURL(string: Router.baseURLString)!
    let URLWithPath = URL.URLByAppendingPathComponent(path)

    let auth = OAuthSwiftClient.authorizationHeaderForMethod(method.rawValue,
        url: URLWithPath,
        parameters: parameters!,
        credential: Router.oauthClient.credential)
    let URLRequest = makeRequest(URLWithPath, method.rawValue, ["Authorization" : auth], parameters!, NSUTF8StringEncoding)

    return URLRequest
  }
}

func makeRequest(URL: NSURL, method: String, headers: [String : String], parameters: Dictionary<String, AnyObject>, dataEncoding : NSStringEncoding) -> NSMutableURLRequest {
var request = NSMutableURLRequest(URL: URL)
request.HTTPMethod = method

for (key, value) in headers {
    request.setValue(value, forHTTPHeaderField: key)
}

let charset = CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(dataEncoding))

var nonOAuthParameters = parameters.filter { key, _ in !key.hasPrefix("oauth_") }

if nonOAuthParameters.count > 0 {
    if request.HTTPMethod == "GET" || request.HTTPMethod == "POST" {
        let queryString = nonOAuthParameters.urlEncodedQueryStringWithEncoding(dataEncoding)
        request.URL = URL.URLByAppendingQueryString(queryString)
        request.setValue("application/x-www-form-urlencoded; charset=\(charset)", forHTTPHeaderField: "Content-Type")
    }
    else {
        var error: NSError?
        if let jsonData: NSData = NSJSONSerialization.dataWithJSONObject(nonOAuthParameters, options: nil, error: &error)  {
            request.setValue("application/json; charset=\(charset)", forHTTPHeaderField: "Content-Type")
            request.HTTPBody = jsonData
        }
        else {
            println(error!.localizedDescription)
        }
    }
}
return request
}
Gautier
  • 47
  • 1
  • 13
  • What is your server DB and what level of unified support does have and is configured for. – zaph Aug 23 '15 at 19:58
  • I have the same app in Obj-C and the server works fine with it so I guess the problem doesn't come from it. – Gautier Aug 24 '15 at 12:50

1 Answers1

0

Converting é to \U00e9 is not a problem, it's part of the JSON spec, which says:

Any character may be escaped. If the character is in the Basic Multilingual Plane (U+0000 through U+FFFF), then it may be represented as a six-character sequence: a reverse solidus, followed by the lowercase letter u, followed by four hexadecimal digits that encode the character's code point. The hexadecimal letters A though F can be upper or lowercase. So, for example, a string containing only a single reverse solidus character may be represented as "\u005C".

If your server can't understand it, it's a problem that your server isn't following the spec.

Aaron Brager
  • 65,323
  • 19
  • 161
  • 287
  • I have the same app in Obj-C and the server works fine with it so I guess the problem doesn't come from it. – Gautier Aug 24 '15 at 12:50