Jeyanth
Jeyanth

Reputation: 59

error while converting NSData objectiveC code to swift

I tried converting this code in Objective C to Swift,

- (IBAction) sendMessage {

    NSString *response  = [NSString stringWithFormat:@"msg:%@", inputMessageField.text];
    NSData *data = [[NSData alloc] initWithData:[response dataUsingEncoding:NSASCIIStringEncoding]];
    [outputStream write:[data bytes] maxLength:[data length]];
    inputMessageField.text = @"";

}

below is my swift code.

@IBAction func sendMessage() {

        var response  = NSString.localizedStringWithFormat("msg:\(inputMessageField?.text)")
        var data = NSData(Data :response , dataUsingEncoding:NSASCIIStringEncoding)
        outputStream(write:data.bytes, maxLength:data.length);
        inputMessageField?.text = ""

    }

I get an error telling that a data is an extra argument. Please help me solve this.

Upvotes: 3

Views: 988

Answers (2)

arthankamal
arthankamal

Reputation: 6413

The method you're looking for NSData(Data :response , dataUsingEncoding:NSASCIIStringEncoding) does not exist.

you can convert like this

var data = NSData(data :response.dataUsingEncoding(NSASCIIStringEncoding)!)


UPDATED

The method outputStream.write() expects UInt8[] array, so you've to convert your data to UInt8[] Array.

Your code should be,

@IBAction func sendMessage() {
    var response  = NSString.localizedStringWithFormat("msg:\(inputMessageField?.text)")
    var data = NSData(Data :response , dataUsingEncoding:NSASCIIStringEncoding)        
    outputStream.write(UnsafePointer(data.bytes), maxLength:data.length)
    inputMessageField?.text = ""
}

Upvotes: 0

Matthias Bauch
Matthias Bauch

Reputation: 90117

There is no NSData(Data :response , dataUsingEncoding:NSASCIIStringEncoding) method. You are probably looking for

let data = 
response.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)

your whole code should look like this:

let response  = NSString.localizedStringWithFormat("msg:\(inputMessageField?.text)")
if let data = response.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {
    outputStream(write:data.bytes, maxLength:data.length);
    inputMessageField?.text = ""
}
else {
    println("could not convert response \"\(response)\" to NSData")
}

use let when ever possible, and check if the failable initalizers return a value

Upvotes: 1

Related Questions