URLSession Conversion to Swift 3

时间:2016-11-12 05:40:21

标签: swift swift3 nsurlsession

I have converted to Swift 3 and receiving the error message

'Cannot convert value of type (UnsafeRawPointer, NSRange, UnsafeMutablePointer)->() to (UnsafeBufferPointer, Data.index, inout Bool)-> Void.

My code:

func urlSession(_ session: URLSession, dataTask: URLSessionDataTask,
didReceive data: Data) {
        data.enumerateBytes{[weak self]
        (pointer: UnsafeRawPointer,
        range: NSRange,
        stop: UnsafeMutablePointer<ObjCBool>) in
        let newData = Data(bytes: UnsafePointer<UInt8>(pointer), count: range.length)
        self!.mutableData.append(newData)
    } }

What do I need to adapt to make it work?

2 个答案:

答案 0 :(得分:1)

You are already getting Data object and you want to append the data, then why are you doing all these things

func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data){
    responseData?.append(data)
}

This will work fine.

For reference, look at https://github.com/ankitthakur/SwiftNetwork/tree/master/Sources/Shared

答案 1 :(得分:0)

When you try to write method it's gives you hint

func urlSession(_ session: URLSession, dataTask: URLSessionDataTask,
                    didReceive data: Data) {
        data.enumerateBytes { (<#UnsafeBufferPointer<UInt8>#>, <#Data.Index#>, <#inout Bool#>) in
            <#code#>
        }

    }

parameter with <# #> coming you just need give local variable name for those that all, so you will get the value in those variable.

Just write like below:

func urlSession(_ session: URLSession, dataTask: URLSessionDataTask,
                didReceive data: Data) {
    data.enumerateBytes { ( buffer ,  index, boolvalue) in

    }
}

I am also learning swift, just let me know any one who make this answer better.