Search code examples
iosswiftcore-datansdata

convert a nsdata into string in swift


I want to convert my saved image in CoreData to String so that I can use it (I don't want to convert it directly into an image as I need to send the image/string to next page too).

Here is my code that I am trying but get BAD_EXC_Result during run time as it found nil value but tableImageArray[indexPath.row] has the value as I pass it to if statement:

if tableImageArray[indexPath.row] != "" {                
    var  _Image:String = String(data: tableImageArray[indexPath.row], encoding:NSUTF8StringEncoding)!   
    //(NSString(data:tableImageArray[indexPath.row], encoding:NSUTF8StringEncoding)) as String!
    print(_Image)
}

Solution

  • This is just my guess.

    Judging from the name of the array, tableImageArray sounds like an array of images, not strings. So I guess you are trying to convert an image to an NSData, and convert that NSData to a string.

    However, that doesn't work. Just like converting directly from an UIImage to a String doesn't work.

    I guess you have either of these intentions:

    1) you want to base64 encode the image to a string. To do this, you just call base64EncodedStringWithOptions([]) on the data.

    2) you want to identify and print a string contained in the UIImage. For this you should probably use some OCR libraries. Just Google them!