Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append two NSData variable in swift?

Tags:

ios

swift

nsdata

I want to append two NSData:

    var actionIdData :NSData = NSData(bytes: &actionId, length: 2)
    var payLoad : NSData = NSData(bytes: &message, length: 9)

    var messageData : NSMutableData!

    messageData.appendData(actionIdData)
    messageData.appendData(actionIdData)

fatal error: unexpectedly found nil while unwrapping an Optional value

like image 495
Meysam Hasanloo Avatar asked Sep 03 '16 08:09

Meysam Hasanloo


2 Answers

Compatible with both Swift 4 and Swift 5 you can only use append function of Data to append two different data.

Sample Usage

guard var data1 = "data1".data(using: .utf8), let data2 = "data2".data(using: .utf8) else {
    return
}

data1.append(data2)
// data1 is now combination of data1 and data2
like image 143
abdullahselek Avatar answered Oct 25 '22 16:10

abdullahselek


You need to initialize your messageData before appending to it.

var messageData = NSMutableData() //or var messageData : NSMutableData = NSMutableData()
messageData.appendData(actionIdData)
messageData.appendData(payLoad)
like image 21
Nirav D Avatar answered Oct 25 '22 14:10

Nirav D