How to use stringWithContentsOfURL:encoding:error:

本文探讨了在iOS开发中使用initWithContentsOfURL方法时遇到的编码问题,并提供了解决方法,包括检查文件编码、尝试不同编码选项等。

I am trying to use initWithContentsOfURL:encoding:error: like this :


NSURL *url = [[NSURL alloc] initWithString:@"http://my_url.com/my_file.xml"];
NSError *error = nil;
NSString *my_string = [[NSString alloc] initWithContentsOfURL:url
encoding:NSUTF8StringEncoding
error:&error];

I get a empty my_string variable.

I tried the initWithContentsOfURL: method (which is deprecated in iOS 2.0) and I get the content of my page. But I still need to specify a encoding language.

What's wrong ?

Thanks :)

share | improve this question
 
 
have you checked the error code? –   Nick Moore  Oct 22 '10 at 10:02
 
Here is the error message : Error Domain=NSCocoaErrorDomain Code=261 "The operation couldn’t be completed. (Cocoa error 261.)" UserInfo=0x6a10230 {NSURL=my_url.com/my_file.xml, NSStringEncoding=4} –   Pierre Espenan  Oct 22 '10 at 10:34 
add comment

3 Answers

up vote 20 down vote accepted

the encoding of your file is probably not UTF8.

If you don't know the encoding of your file, you could try this method:

- (id)initWithContentsOfURL:(NSURL *)url usedEncoding:(NSStringEncoding *)enc error:(NSError **)error

you have to pass a pointer to a NSStringEncoding, like you did with error.:

NSURL *url = [[NSURL alloc] initWithString:@"http://my_url.com/my_file.xml"];
NSError *error = nil;
NSStringEncoding encoding;
//NSString *my_string = [[NSString alloc] initWithContentsOfURL:url
//                                                     encoding:NSUTF8StringEncoding
//                                                        error:&error];
NSString *my_string = [[NSString alloc] initWithContentsOfURL:url
                                                 usedEncoding:&encoding 
                                                        error:&error];

after this your encoding is present in the encoding variable. If you are not interested in the used encoding, I guess you could pass NULL as pointer as well.

share | improve this answer
 
 
I tried to change UTF8 to ISOLatin1 (ISOLatin2 works as fine as UTF8). It partially worked : I still have issues with î, ', ô, ... –   Pierre Espenan  Oct 22 '10 at 11:47
 
And How do you use initWithContentsOfURL:usedEncoding:error: ? What is the second parameter ? –  Pierre Espenan  Oct 22 '10 at 11:48 
 
@Nonepse I made an edit. HTH –   Matthias Bauch  Oct 22 '10 at 12:29
 
Saw that, thanks, but it's still not working (my_string is null). Anyway, I manually replaced the few characters which were not encoded. –   Pierre Espenan  Oct 22 '10 at 12:47 
 
of course if your file is not encoded correctly in any encoding supported by the iphone it can't be decoded properly. –   Matthias Bauch  Oct 22 '10 at 12:50
show 2 more comments

Why not use a request and connection to get the info back in an NSData object? Something like this:

NSURL *url = [[NSURL alloc] initWithString:@"http://my_url.com/my_file.xml"];

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:url];
[request setHTTPMethod:@"GET"];

NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];

    [conn start];

if(conn){
    // Data Received
    responseData = [[NSMutableData alloc] init];
}

and then in your connection:didRecieveData delegate method, put something like this

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

[self.responseData appendData:data];
}

and then once the connection is finished loading convert the data to a string:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
     NSString *string = [[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding];
}

Not the most straightforward method, but that should get you your XML string. Also if you need to parse the XML once you get it back, you can directly pass the responseData to an NSXMLParser without any conversion. :)

share | improve this answer
 
 
This assumes that the responses' body is in ASCII, which is still the exact same error that the original question has. You must determine encoding type from the response. –   Brent  Feb 6 '13 at 0:56
add comment

You can modify your webpage by adding header('Content-Type: text/html; charset=UTF-8'); to the top of the code and saving the document as a UTF-8 formated file. It helped me as I had the same problem.

share | improve this answer

转自http://stackoverflow.com/questions/3995519/how-to-use-stringwithcontentsofurlencodingerror/3995954#3995954
### Key Exchange Identification Connection Issue Solution Key exchange identification plays a critical role in establishing secure and authenticated connections between entities. When dealing with connection issues related to key exchange identification, several factors must be considered, including the cryptographic protocols used, the integrity of public/private keys, and potential vulnerabilities in the implementation[^1]. A common issue arises when a third party (C) uses mechanisms to impersonate another entity (A). For example, C might exploit A's use of its public/private key pair for both authentication and digital signatures, leading to unauthorized message signing. This situation highlights the importance of segregating key usage for different purposes[^1]. To mitigate this risk, organizations should adopt best practices such as issuing separate key pairs for authentication and signing. Additionally, remote procedure calls (RPCs) can introduce challenges due to their inherent transparency assumptions. In cases where RPCs fail, the client or server may experience crashes, network disruptions, or other errors. Programs relying on RPCs must implement robust error-handling mechanisms, either by testing for failures explicitly or catching exceptions during execution[^2]. These measures help ensure that the application remains resilient even under adverse conditions. Another consideration involves adhering to well-established standards and guidelines during protocol implementation. RFC documents often provide detailed specifications for ensuring interoperability, performance, and robustness across systems. Developers should strive to create good-faith implementations based on thorough analysis of these documents and engagement with relevant technical communities[^3]. Such an approach minimizes discrepancies and enhances overall system reliability. Below is an example of how key exchange identification could be implemented securely using Python: ```python import cryptography.hazmat.primitives.asymmetric.rsa as rsa from cryptography.hazmat.primitives import serialization, hashes from cryptography.hazmat.primitives.asymmetric import padding # Generate RSA key pair private_key = rsa.generate_private_key( public_exponent=65537, key_size=2048 ) public_key = private_key.public_key() # Serialize public key for exchange pem = public_key.public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo ) # Sign a message using the private key message = b"Secure Message" signature = private_key.sign( message, padding.PSS( mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH ), hashes.SHA256() ) # Verify the signature using the public key try: public_key.verify( signature, message, padding.PSS( mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH ), hashes.SHA256() ) print("Signature is valid.") except Exception as e: print("Signature verification failed:", e) ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值