problem with getting image string in json swift 5 [duplicate] - swift

This question already has answers here:
Swift - encode URL
(19 answers)
Closed 1 year ago.
I want to download image and when I run app my app crashed because the image string of json file is like this :
images/product/2021-05-02T09-47-17.699Z-download (2).jpg
there is a distance between download and (2) in my json file and its the problem that make an app crash , in browser its worked but in Xcode not , what's your idea to solve it?
and here is a part of my code when I want to download image :
let imageUrl = URL(string: "http://5.63.13.16:8080/\(item.image.first!)")!
if let data = try? Data(contentsOf: imageUrl) {
cellol.offerImageView.image = UIImage(data: data)
}

you can just use it
func stringCorrection( _ text:String) -> String{
return text.replacingOccurrences(of: " ", with: "", options: NSString.CompareOptions.literal, range: nil)
}
use: -
let imageUrl = URL(string: "http://5.63.13.16:8080/\(stringCorrection(item.image.first!))")!
if let data = try? Data(contentsOf: imageUrl) {
cellol.offerImageView.image = UIImage(data: data)
}

Related

Why is UIImage? nil here?

I'm trying to bridge React and Swift code by passing a string for an image path, which I've verified appears correctly on the Native side, and having a bit of an issue. The image path comes from React as NSString, and my goal is to pass that as a String to a Native function that will ultimately send data back to React.
Here's a snippet of some code that handles part of this
classifyImage(value as String)
and some of the body of the classifiyImage is as follows:
#objc func classifyImage(_ image: String) {
let imageData = Data(base64Encoded: image, options: .ignoreUnknownCharacters)!
let uiImage = UIImage(data: imageData)
guard let orientation = CGImagePropertyOrientation(
rawValue: UInt32((uiImage?.imageOrientation.rawValue)!)) else {
return
}
...code
}
The exact error is at the line with the rawVale, reading
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
Here's more info if it may help...
Image data can come from the camera as such image NSMutableString "file:///var/mobile/Containers/Data/Application/54691469-2196-444E-9B45-C0D6F2CABEBC/Library/Caches/Camera/EEC3631C-3E96-44DA-B258-411363A2F10C.jpg" 0x00000002815a8420
or from the phone's gallery image String "ph://8F109DC0-CE95-4D0A-9D11-1B2E9CE6B8D3/L0/001"
Image from a file
First, we need to turn the string into a URL, then the URL into data like so:
let url = URL(string: image)
do {
let data = try Data(contentsOf: url)
} catch {
print(e)
}
Then we can use it to create the image.
do {
let data = try Data(contentsOf: url)
let image = UIImage(data: data)
guard let orientation = CGImagePropertyOrientation(
rawValue: UInt32(image.imageOrientation.rawValue)) else {
print("that didn't work")
return
}
} catch {
print(e)
}

How to open .pdf URL in Safari browser in swift [duplicate]

This question already has answers here:
Swift - encode URL
(19 answers)
How to use stringByAddingPercentEncodingWithAllowedCharacters() for a URL in Swift 2.0
(6 answers)
Closed 3 years ago.
Here i trying to open URL with .pdf extension in Safari Browser. But code is not working I'm getting nil in URL. But when i tried URL like "www.google.com" it's working fine
Code
let cerificateURl = "https://file-examples.com/wp-content/uploads/2017/10/file-sample_150kB.pdf"
guard let url = URL(string: cerificateURl) else {
return
}
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(url)
}
Thanks in Advance
Try this one:
guard let url = URL(string: "your web pdf file link here or you can set from local directory path")
else { return }
UIApplication.shared.open(url)
Try This one.
let cerificateURl = "https://file-examples.com/wp-content/uploads/2017/10/file-sample_150kB.pdf"
if let myURL = URL(string: url) {
if let data = try? Data(contentsOf: myURL) {
webView.load(data, mimeType: "application/pdf", characterEncodingName: "", baseURL: myURL
}
}

Cannot convert URL to Data(contentsOf: URL) in swift5

I know there are many solutions around related to converting an Image string into data and to set the image in an ImageView. But unfortunately, nothing worked in my case. I have a parsed JSON field which returns an Image as a string. So I'm trying to convert that String as URL and then to get URL data to display the image. But when the error is throwing when I try to get the data from URL like
let testImage = Data(contentsOf: forecastURL! as URL)
Error: "Incorrect argument label in call (have 'contentsOf:', expected
'dictionary:')"
if let url21 = URL(string: brandingLogo) {
do {
let testImage = Data(contentsOf: url21)
self.BrandingBarImage.image = UIImage(data: testImage)
}
catch
{
print("error")
}
}
**Code for brandingLogo:**
guard let url = URL(string: urlJson) else {return}
let task = URLSession.shared.dataTask(with: url) { (data1, response, error) in
do {
let parsedData = try JSONSerialization.jsonObject(with:data1!) as? [String:Any]
let statusList = parsedData?["data"] as? [String:Any]
let anotherData = statusList?["data"] as? [String:Any]
if let players = anotherData?["players"] as? [[String:Any]] {
for logo in players {
self.brandingLogo = logo["logo_app_branding_bar"] as? String
print(self.brandingLogo)
}
brandingLogo is parsed from Json and its value is: https://media.socastsrm.com/wordpress/wp-content/blogs.dir/223/files/2018/01/blank-300x95.png
so, I'm assuming that when this 'brandingLogo' is considered as String, it takes only the actual string like :
https://media.socastsrm.com/wordpress/wp-content/blogs.dir/223/files/2018/01/blank-300x95.png
And so I'm trying to convert that image string to URL and then to get Data
Any help is appreciated. Thank you

Display Image on a button from a URL in swift

I need to display the background image of a button by giving the image source from an external URL instead of downloading the image. Is there a possible way to do this in swift.
You can use SDWebImage POD.
yourBtn.sd_setImage(with: <#T##URL?#>, for: <#T##UIControl.State#>, completed: <#T##SDExternalCompletionBlock?##SDExternalCompletionBlock?##(UIImage?, Error?, SDImageCacheType, URL?) -> Void#>)
First you need to get the image data from external URL and then use the image
if let url = URL(string: "YOUR-IMAGE-URL-HERE") {
do{
let data = try Data(contentsOf: url)
self.imageVar = UIImage(data: data)
if let myImage: UIImage = self.imageVar {
YOUR-BUTTON-NAME.setImage(myImage, for: .normal)
}
}catch {
print("error")
}
}

Display base64 encoded image in imageview: SWIFT 3

I have base64 image string which is downloaded from a webpage using POST request and I am trying to decode and display inside imageview but it's not working. I have tried couple of sources but no luck :(
let base64String = "data:image/jpg;base64,/9j/4aaQSkZJRg0BMADAE15a5df.....H/12Q=="
Currently, trying this method:
if let decodedData = Data(base64Encoded: base64String, options: .ignoreUnknownCharacter) {
let image = UIImage(data: decodedData)
ImageView.image = image
} else {
print("error in decoding")
}
Tried NSData method also:
let dataDecode:NSData = NSData(base64Encoded: base64String!, options:.ignoreUnknownCharacters)!
let image= UIImage(data: dataDecode as Data)!
yourImageView.image = image
The else part always executes. I have tried this in xCode playground by putting encoded string in static variable and noticed nil in front of if condition line.
Not sure, what I am doing wrong?
Your base64String is actually a URL with a data scheme. There is built in support for these types of URLs.
You can do something like:
let dataString = "data:image/jpg;base64,/9j/4aaQSkZJRg0BMADAE15a5df.....H/12Q=="
let dataURL = URL(string: dataString)
let data = Data(contentsOf: dataURL)
let image = UIImage(data: data)
I leave it as an exercise to properly handle optional values and error handling.
be careful, only part of the string represents the image
let base64String = "data:image/jpg;base64,9j/4aaQSkZJRg0BMADAE15a5df.....H/12Q=="