1

I want to create a wrapper around the NSURLSession and I found some nice code but was written in Swift.https://github.com/daltoniam/SwiftHTTP.But since I still write production code in Objective-C I started borrowing the idea of the above code, though I have hard time to understand the following code and translate to Objective-C (if needed). I know I could use AFNetworking but this is not feasible due to architecture decisions when building a distributable framework.

The code:

    /// encoding for the request.
    public var stringEncoding: UInt = NSUTF8StringEncoding

// Somewhere in a method

    var charset = CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(self.stringEncoding));
if request.valueForHTTPHeaderField(contentTypeKey) == nil {
                    request.setValue("application/x-www-form-urlencoded; charset=\(charset)",
                        forHTTPHeaderField:contentTypeKey)
                }
                request.HTTPBody = queryString.dataUsingEncoding(self.stringEncoding)

My Objective-C code:

@property (assign, nonatomic) NSUInteger stringEncoding;

    // In this line I get a compiler warning and in runtime it crashes with BAD_EXC
        CFStringEncoding cfStringEncoding = CFStringConvertIANACharSetNameToEncoding(CFStringConvertNSStringEncodingToEncoding(self.stringEncoding));
                if (![mutableRequest valueForHTTPHeaderField:ContentTypeKey])
                    {
                    [mutableRequest setValue:[NSString stringWithFormat:@"application/x-www-form-urlencoded; charset=%u", (unsigned int)cfStringEncoding] forHTTPHeaderField:ContentTypeKey];
                    }
                mutableRequest.HTTPBody = [queryString dataUsingEncoding:self.stringEncoding];

Compiler warning:

Incompatible integer to pointer conversion assigning to 'CFStringEncoding' (aka 'unsigned long') from 'CFStringRef' (aka 'const struct __CFString *')

I don't have strong experience working with CFStringEncoding and CFString so I find it hard to translate the documentation.

Do I really need this conversion, and what is it's purpose?

George Taskos
  • 8,324
  • 18
  • 82
  • 147
  • 1
    You ObjC code seems to use the wrong function (CFStringConvertIANACharSetNameToEncoding instead of CFStringConvertEncodingToIANACharSetName). And you cannot print a string with `%u` ... – Martin R Feb 27 '15 at 17:04
  • They typo was wrong and I couldn't see it!! I used the answer below in the end. – George Taskos Feb 27 '15 at 17:08

1 Answers1

0

Try using NSString instead:

NSString *charset =
        (NSString *)CFStringConvertEncodingToIANACharSetName
        (CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));

This is what typically was used before the Swift version, and as I recall AFNetworking used a similar method (if not the same).

l'L'l
  • 44,951
  • 10
  • 95
  • 146