简体   繁体   中英

String.encode is failing with cannot be performed with encoding 'UTF-8' because Apple's ICU doesn't allow it

I am working on iOS7 with RubyMotion 2.34, Motion-bundler 0.2.1, and rubysl-rexml 2.4.1.

I've gotten the following error when trying to parse an XML response from a server, down in the encoding part of REXML. However, I've also done the following to isolate the problem, which is what REXML library does to the string it is given:

def content
    @s = @response.body.to_s
    puts @s.encoding
    @s.encode("UTF-8")
end

where @response is the return from AFMotion::HTTP.get("http://....") call. It's just a simple XML string with nothing but plain US-ASCII characters in it. I get the following error:

2014-10-02 18:34:14.714 promotion-motion-kit[44375:1346884] *** Terminating app due to uncaught exception 'RuntimeError', reason: 'http_client.rb:17:in block in content': this operation cannot be performed with encoding UTF-8' because Apple's ICU does not support it (RuntimeError) from http_client.rb:15:in `content'

I also get the EXACT same error (noting the UTF-8) when I change the code to:

@s.encode("US-ASCII")

So, it seems that it does not matter what I give String#encode as long as it is a valid encoding name.

UPDATE: This error raises with ANY string I use, such as:

"hello".encode("UTF-8")

Doesn't anybody know how to rectify this situation?

Ack, sorry to hear that. I still prefer working with RubyMotion over raw Objective-C.

Although I don't have a perfect solution, I have a decent workaround, at least in my case. For me, 99.9% of my input will already be in utf8 format, and the string will show that it has that encoding. So I've overridden the encode method to check for that case.

class String alias_method :orig_encode, :encode def encode(encoding) return self if self.encoding.to_s == encoding orig_encode(encoding) end end

Also, the method String.force_encoding('UTF-8') also works, though as I understand it, if there is an actual error during the encoding, the error doesn't get raised (as it would in the normal encode method). But depending on your usage, that may be ok.

At least for me, this should work until RubyMotion gets this (what I consider) bug fixed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM