Ios – Cannot convert value of type ‘UInt’ to expected argument type ‘UnsafeMutablePointer

iosswift

I am trying to initialize a String from the content accessible by a URL:

actualresponse.response = String(contentsOfURL: url, usedEncoding: NSUTF8StringEncoding)

I get the following error thrown, pointing at the usedEncoding:

Cannot convert value of type 'UInt' to expected argument type 'UnsafeMutablePointer'

Can anyone tell me why this error is thrown and how I can fix it?

Best Answer

There are two similar but different methods which can be mistaken.

  • The usual method is

    init(contentsOfURL url: NSURL,
        encoding enc: UInt) throws
    

    The encoding parameter takes an NSStringEncoding value to specify the encoding, for example

    let string = try? String(contentsOfURL:url, encoding:NSUTF8StringEncoding)
    

  • The second method retrieves the encoding from the file by passing a pointer as usedEncoding parameter

    init(contentsOfURL url: NSURL,
        usedEncoding enc: UnsafeMutablePointer<UInt>) throws
    

    The documentation says:

    Upon return, if url is read successfully, contains the encoding used to interpret the data.

    That means you have to pass a pointer which will contain the determined encoding of the file.

    var encoding : NSStringEncoding = 0
    let string = try? String(contentsOfURL:url, usedEncoding:&encoding)
    
Related Topic