get a string from UIImage in swift - ios

I have image loaded from UIImagePickerController into UIImageView
I need to convert the image into string to send it to the server
This is my code but it gives an error
var imageData:String = "";
if let unwrappedImage = profileImage.image {
let imageNSData : NSData = UIImageJPEGRepresentation(unwrappedImage, 1.0)!;
imageData = (NSString(data:imageNSData, encoding:NSUTF8StringEncoding) as String?)!
}
I am getting the following exception
fatal error: unexpectedly found nil while unwrapping an Optional value
can any one help please

Convert the data information of a image to a string , you will get a very very very long string, why not loaded the data to the server. Alamofire can do it easily, just see the uploading file part.

Related

Converting Base64 to data returning nil

I am trying to convert base64 string to image, I checked the json response, base64 string is not empty, but Data returns nil in between.
let base64String = image.Image_bytes_1
var data = Data(base64Encoded: base64String!, options: .ignoreUnknownCharacters)
let image = UIImage(data: data! as Data)
imageView.image = image
at line#4 getting this below error
Thread 3: Fatal error: Unexpectedly found nil while unwrapping an
Optional value
The Data initializer you are using, init(base64Encoded:options:) is declared as init?(base64Encoded base64Data: Data, options: Data.Base64DecodingOptions = [])
That's known as a "failable initializer", which means it can return nil. (note the question mark after init in the declaration.)
If the base64 data is not well-formed, it may fail and return nil.
Stop using force-unwrapping. Rewrite using optional binding:
if let base64String = image.Image_bytes_1,
let data = Data(base64Encoded: base64String, options: .ignoreUnknownCharacters),
let image = UIImage(data: data) {
imageView.image = image
} else {
print("Unable to load base64 data and convert to image")
}
Edit:
As workingdog pointed out in their comment, your code does not make sense:
let base64String = image.Image_bytes_1 // line 1
var data = Data(base64Encoded: base64String!, options: .ignoreUnknownCharacters) // line 2
let image = UIImage(data: data! as Data) // line 3
imageView.image = image // line 4
Line 1 references something called image. You don't show the code that declares it, so we don't know what it is.
Then in line 3, you declare a new local constant also named image. If the original image is an instance variable of your class, and the code you posted is inside a function, you are creating a new local variable that overrides the other variable called image. I strongly advise against using the same variable name in different levels of scope. That is confusing at best, and causes errors at worst.

Decode Data that is base64String to String utf Swift

A library save a token as Data in UserDefaults
//loading the token
if let token = UserDefaults.standard.object(forKey: "token") as? Data {
let base64Encoded = token.base64EncodedData
let base64EncodedString = token.base64EncodedString()
}
When I print that base64Encoded value in the console I get the value: Y2E2N2Y5NTItNDVkOC00YzZkLWFkZDMtZGRiMjc5NGE3YWI2OjdmZDU1ZTAyLWExMjEtNGQ1ZC05N2MzLWM5OWY4NTg5NTIzNg== as Data
When I copy this value from the output in the console and use this website https://www.base64decode.org/ I got the expected result. ca67f952-45d8-4c6d-add3-ddb2794a7ab6:7fd55e02-a121-4d5d-97c3-c99f85895236
My problem is that I don't get convert that base64Encoded to String in my code.
When I use base64EncodedString I got a string, but I can't figure out which format this is: PFsYdirs21247rRG/XcWOVGUGUcCCTzXz7VFAnunLJU= The method base64EncodedString() This is an method from Apple: https://developer.apple.com/documentation/foundation/nsdata/1413546-base64encodedstring
When I decode this value to utf8 at the website I got: <[v*]Fw9QG
When I try to convert my base64Encoded (Data, not String) to a string like this
if let toString = String(data: base64Encoded, encoding: String.Encoding.utf8) as String {
print("test \(toString)")
}
my compiler threw an error: Cannot convert value of type(Data.Base64EncodingOptions) -> Data to expected argument type Data
Here I found a solution to decode when my Data-value would be a string.
https://stackoverflow.com/a/31859383/4420355
So I'm quite confused about the results. Long story short:
I have base64Encoded Data (Y2E2N2Y5NTItNDVkOC00YzZkLWFkZDMtZGRiMjc5NGE3YWI2OjdmZDU1ZTAyLWExMjEtNGQ1ZC05N2MzLWM5OWY4NTg5NTIzNg==) and want them convert to an utf8 string. I don't get handle this.

UIImage to NSData fatal error: unexpectedly found nil while unwrapping an Optional value

I use NSData to convert UIImage from photolibrary to NSData but it gives.
error fatal error: unexpectedly found nil while unwrapping an Optional
value
Following is my code
if(o.count == 1)
{//o is [UIImage]
let imgdata:NSData? = UIImageJPEGRepresentation(self.o[0], 10)
print(o[0]) //it show <UIImage: 0x14e123cb0>, {30, 40}
print(imgdata)
}
if o.count == 0, the array is empty. So you are trying to create NSData from an empty array here
UIImageJPEGRepresentation(self.o[0], 10)
It's safer to do
if let imgdata = UIImageJPEGRepresentation(self.o[0], 10) {
...
}
So your app doesn't crash if it returns nil. Swift knows that UIImageJPEGRepresentation returns NSData, so you don't need the :NSData? in the if statement.
Hope this helps!

IOS Swift Unwrapping NSData is Crashing

IOS swift problem while unwrapping, crashing. I am getting data as NSData, when I am printing in string or
var dict : AnyObject = NSJSONSerialization.JSONObjectWithData(returnData!, options: NSJSONReadingOptions(0), error: &respError) as AnyObject!
doing this its returning dict nil,
or
var datastring : NSString = NSString(data:returnData!, encoding:NSUTF8StringEncoding)[This is My Image Liknk] as! String
datastring causing fatal error:
unexpectedly found nil while unwrapping an Optional value.
You are unwrapping the values forcefully (Forced Unwrapping), If that object contains nil then it will generate runtime error.
Trying to use ! to access a non-existent optional value triggers a
runtime error. Always make sure that an optional contains a non-nil
value before using ! to force-unwrap its value.
You would do well to check all your values before you assume they're not nil. With the "!" you tell your code that this value can be safely unwrapped even though it may still be nil. Hence when it is nil, it crashes. What I usually do is:
// Unwrap the string, check if it ain't nil and store this in a new value.
if let content: String = item.content as? String {
if content != "" {
var error: NSError?
// Unwrap the data optional from dataUsingEncoding and also check if it ain't nil. Store this in a new value.
if let data: NSData = content.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true),
// Unwrap the optional returned from JSONObjectWithData and also check if it ain't nil. Store the value in a new object.
let json: NSMutableDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as? NSMutableDictionary {
// Do stuff with the dictionary.
} else {
if let err: NSError = error {
println(err.localizedDescription)
}
}
}
}
With all these checks I am sure my code will not crash deserializing the string to json in swift.
It appears I was a bit slow with my answer but Nilesh Patel has a good quote there which you should look at.
It is because returnData! is nil. If you put a break point at var dict, run and then po returnData! I believe you will find that to be true. And because the data at which NSJSONSerialization is trying to accept as a parameter is nil, it will be as well. I would go through your logic or your source to figure out why it is nil.
Also if you are using NSURLSession to retrieve your data - make sure you have a valid configured session before calling dataTaskWithURL. Like so...
var config = NSURLSessionConfiguration.defaultSessionConfiguration()
var session = NSURLSession(configuration: config)
var dataTask:NSURLSessionDataTask = session.dataTaskWithURL...
I ran into this problem and figured out that the session needed to be configured before I called the data task.
EDIT Also try this. Use optional binding.
if let data: NSDictionary = NSJSONSerialization.JSONObjectWithData(returnData, options: NSJSONReadingOptions.AllowFragments, error: nil) as? NSDictionary {
println("json = \(data)")
}
else {
println("returnData really is nil")
}

NSString to String throwing "fatal error: unexpectedly found nil while unwrapping an Optional value"

The following Swift code is crashing on the return statement with the following error:
fatal error: unexpectedly found nil while unwrapping an Optional value
According to the debugger the result variable has a non-null value. I really want the function to accept Strings and return a String, not NSData. Hoping this is a dumb question and I'm just not seeing it. Been stuck on this for hours!
println(hmac_sha256("sample_data", inKey: "sample_key"))
func hmac_sha256(inData: String, inKey: String) -> (String) {
let data: NSData = inData.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
let key: NSData = inKey.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
var result = NSMutableData(length: Int(CC_SHA256_DIGEST_LENGTH))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), key.bytes, size_t(key.length), data.bytes, size_t(data.length), result!.mutableBytes)
return NSString(data: result!, encoding: NSUTF8StringEncoding) as! String
}
You cannot expect to be able to turn arbitrary data into an NSString with UTF-8 encoding. For example, UTF-8 can never, ever include a byte 0xff and therefore data containing that byte value can never be turned into an NSString.
So no matter how hard you want to get an NSString, you won't get it.
Got it. I think I was missing the big picture. The goal was to convert NSData to a hex string. I found a nifty method on github for this here: https://github.com/CryptoCoinSwift/SHA256-Swift/blob/master/SHA256.swift

Resources