Incorrect NSStringEncoding value 0x0000 detected (using ASIHTTPRequest)

前端 未结 1 1834
执笔经年
执笔经年 2021-02-13 19:55

I\'m using ASIHTTPRequst in my application and im having some problems, but only on certain devices. In some cases i get the following error:

\" Incorrect NSStringE

1条回答
  •  名媛妹妹
    2021-02-13 20:39

    Copying my answer from https://stackoverflow.com/q/8251175/918764 - you're most likely getting this message because of you're calling getResponseString on a request that has failed. You should make sure that you check if you got a response before calling this: one way I've found to test for total request failure (i.e. network/server down) is to check:

    if (request.responseStatusCode == 0) {
        // the request failed entirely
    } else {
        // you at least got a HTTP response
    }
    

    This notably happens if you call [asiHttpRequest getResponseString] before a valid response has been returned and the request encoding has been set (i.e. couldn't connect to server).

    The easiest way to workaround this warning is by editing the ASIHTTPRequest class, remove the @synthesize responseEncoding and adding a simple custom getter/setter so you can return the default encoding if the response encoding isn't set:

    - (NSStringEncoding) responseEncoding
    {
        return responseEncoding || self.defaultResponseEncoding;
    }
    
    - (void) setResponseEncoding:(NSStringEncoding)_responseEncoding
    {
        responseEncoding = _responseEncoding;
    }
    

    There's also a more specific workaround for the getResponseString method, which I think is the only place that uses the encoding without checking for a value - since the encoding should be set for any non-zero length response:

    - (NSString *)responseString
    {
        NSData *data = [self responseData];
        if (!data) {
            return nil;
        }
        // --- INSERT THIS BLOCK ---
        // If the 'data' is present but empty, return a simple empty string
        if (data.length == 0) {
            return @"";
        }
        //assert(self.responseEncoding); // if you're into runtime asserts, uncomment this
        // --- END OF BLOCK TO INSERT ---
        return [[[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:[self responseEncoding]] autorelease];
    }
    

    0 讨论(0)
提交回复
热议问题