NSData contentsOfURL Returns Nil? - ios

I have the following code
import Foundation
let url = NSURL(string: copiedURL)
let data = NSData(contentsOfURL: url!)
print("\(data)")
let image2 = UIImage(data: data!)
When I build and run, I get the following error fatal error: unexpectedly found nil while unwrapping an Optional value referring to
let image2 = UIImage(data: data!)
I tried to modify my Info.plist with the following
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
But the error is still there. Is there any more possible solutions I can try?

Couple of possibilities here.
The copiedURL is not being properly converted to a NSURL
The NSURL is not being converted to NSData
The image is unable to load the data
Try the following:
if let url = NSURL(string: copiedURL) {
print(url)
if let data = NSData(contentsOfURL: url) {
print(data)
let image2 = UIImage(data: data)
}
}
It's almost never a good idea to force unwrap something (!), instead use guard or if let to unwrap and thus be able to handle the nil condition.
Refer to: Loading/Downloading image from URL on Swift for how to properly download images.

Try the following code:
if let url = NSURL(string: copiedURL) {
if let data = NSData(contentsOfURL: url) {
print("\(data)")
let image2 = UIImage(data: data)
}
}
If copiedURL has valid image you will get it, otherwise atleast your app will not crash.

Related

Convert images from URL returns NSURLConnection finished with error - code -1022

I'm trying to solve this issue:
I know, is very documented
NSURLConnection finished with error - code -1022
xCode 9 - iOS 11: NSURLConnection - sendAsynchronousRequest fails
Well, for some reason, that's not resolve my problem.
I already in my info.plist file:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
All the request, are ok, but, when I try to parse a string base64 to an image, I get the error:
NSURLConnection finished with error - code -1022
That happens exact in this moment:
let image = datasource[i].File!.base64ToImage()
let imageView = UIImageView(image: image)
The message is displayed exactly when I try to convert to UIImageView.
also, I'm using this extension:
func base64ToImage() -> UIImage? {
if let url = URL(string: self),let data = try? Data(contentsOf: url),let image = UIImage(data: data) {
return image
}
return nil
}
The datasource contains the correct info for all the keys (also, are tested).
Someone has an idea about how to solve it?
var base64String: NSString!
let myImage = UIImage(named:"image.png")
let imageData = UIImageJPEGRepresentation(myImage, 0.9)
base64String = imageData!.base64EncodedString(options: NSData.Base64EncodingOptions.endLineWithLineFeed) as NSString!
print(base64String)
Base64String to Data
let thumbnail1Data = Data(base64Encoded: base64String as String, options: NSData.Base64DecodingOptions()
imageView?.image = UIImage(data: thumbnail1Data as Data)

how to load an image from the url getting from server

I am having and imageView and I am getting the userData from the server when loggedIn in the userData I have a parameter for "profilePic":"penguins.jpg". now I am adding the domain like "http://.....(self.userData.value(forKey: "profilePic")!)" and saving this value into a string variable to store and when I am accessing the value and trying to convert the url into data and adding to imageView.image it is throwing : unexpectedly found nil while unwrapping an optional value..
All my other userData like name,address,phoneNumber are showing fine except for Image.
My Code:
here are the some of the many ways I tried:
way:1
let ad : AppDelegate = UIApplication.shared.delegate as! AppDelegate
let imageUrlString = ad.userImagePath
let imageUrl:URL = URL(string: imageUrlString)! // it is throwing error here(: unexpectedly found nil while unwrapping an optional value)
DispatchQueue.global(qos: .userInitiated).async {
let imageData:NSData = NSData(contentsOf: imageUrl)!
DispatchQueue.main.async {
let image = UIImage(data: imageData as Data)
self.profileImage.image = image
}
}
way:2
if let url = NSURL(string: ad.userImagePath) {
if let data = NSData(contentsOf: url as URL){
if let imageUrl = UIImage(data: data as Data) {
profileImage.image = imageUrl
}
}
}
I have tried different ways to solve this, can't figure out what is my mistake.. finally I am here.. Please someone help he...

Fatal error Xcode 8 Swift 3

ok guys can I get a little help with my code. When running the app I get an error is there any way to fix this problem?
let fileUrl = dict["fileUrl"]as! String
let url = NSURL(string: fileUrl)
let data = NSData(contentsOf: url! as URL!)
let picture = UIImage(data: data! as Data!)
let photo = JSQPhotoMediaItem(image: picture)
self.messages.append(JSQMessage(senderId: senderId, displayName: senderName, media: photo))
Image here
Here I see 4 big fat problems with your code.
You are force casting the value of fileUrl of the dictionary dict to String. If your dictionary doesn't have the value for fileUrl, or if it's not castable to string, your code will crash. You should change that to optional cast like:
if let fileUrl = dict["fileUrl"] as? String
{
//your code if you have fileUrl
}
When creating the url to the file, you are using the wrong initialization method, you should be using this:
let url = URL(fileURLWithPath: fileUrl)
After you have the url to the file, you should also check if you have the data of the file, because contentsOfFile: initializer of the NSData returns the optional object, which may be nil, so another if check:
if let data = NSData(contentsOf: url) {\\ code with the data}
init?(data: Data) initializer of the UIImage also returns optional object, so if the required by latter code, you should also check if you have the image or nil with if statement.
The result code should be something like:
if let fileUrl = dict["fileUrl"] as? String {
let url = URL(fileURLWithPath: fileUrl)
if let data = NSData(contentsOf: url) {
let image = UIImage(data: data as Data) // you can cast NSData to Data without force or optional casting
let photo = JSQPhotoMediaItem(image: image)
self.messages.append(JSQMessage(senderId: senderId, displayName: senderName, media: photo))
}
}
Hope this helps.
Replace the first line of code with this line for optional binding check :-
guard let fileUrl = dict["fileUrl"] as! String else {return}
Yo should do validation in cases where the variable may be nil, the following is an example:
if let fileUrl = dict["fileUrl"] as? String {
let url = URL(string: fileUrl)
do {
let data = try Data(contentsOf: url!)
let picture = UIImage(data: data)
let photo = JSQPhotoMediaItem(image: picture)
self.messages.append(JSQMessage(senderId: senderId, displayName: senderName, media: photo))
} catch {
}
}

Fatal Error: Unexpectedly found nil while unwrapping an Optional value NSURL

I getting nil error. But I didnt understand why happaned. I can get selectedPhoto name with print. But I cant use in NSUrl. Could you help me pls?
my codes:
print(selectedPhoto)
if selectedPhoto != nil
{
let photoUrl = NSURL(string: "http://www.kerimcaglar.com/uploads/yemek-resimler/\(selectedPhoto)")
print("photo url: \(photoUrl)")
dataPhoto = NSData(contentsOfURL:photoUrl!)
yemekResim.image = UIImage(data: dataPhoto!)
}
else
{
print("Error")
}
From Apples documentation on NSData(contentsOfURL)
Do not use this synchronous method to request network-based URLs. For network-based URLs, this method can block the current thread for tens of seconds on a slow network, resulting in a poor user experience, and in iOS, may cause your app to be terminated.
If your app crashes because of this it will be rejected from the store.
Instead you should use NSURLSession. With the Async callback block as in my example.
Also it is not a good idea to force unwrap optionals ! as you will get run time errors instead use the if let syntax
See my example below.
if let photo = selectedPhoto{
let photoUrl = NSURL(string: "http://www.kerimcaglar.com/uploads/yemek-resimler/\(photo)")
if let url = photoUrl{
NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: {(data, response, error) in
if let d = data{
dispatch_async(dispatch_get_main_queue(), {
if let image = UIImage(data: d) {
self.yemekResim.image = image
}
})
}
}).resume()
}
}
}
Replace this:
let photoUrl = NSURL(string: "http://www.kerimcaglar.com/uploads/yemek-resimler/\(selectedPhoto)")
with this:
let photoUrl = NSURL(string: "http://www.kerimcaglar.com/uploads/yemek-resimler/\(selectedPhoto!)")
(Notice the "!" after selectedPhoto)

Display image from URL in swift, unwrapping error

I'm trying to display image to imageView from URL. I successfully done it using synchronous method in a simple project. But this application is used for online store, so I took product information and image URL from a JSON file. which I'm sure I was successfully stored all the data in a product array. But the problem I'm facing is this:
fatal error: unexpectedly found nil while unwrapping an Optional value
Here is the code.
// UnWrapping imageURL
let url:NSURL? = NSURL(string: actualCurrentProduct.imageURL)
if let actualURL = url {
let imageData = NSData(contentsOfURL: actualURL)
if let actualImageData = imageData {
self.productImageView.image = UIImage(data: actualImageData)
}
}
It highlighted in this particular code.
self.productImageView.image = UIImage(data: actualImageData)
Anybody have any idea why? Really appreciated it.
I managed to display the image successfully from URL with this code. I started the project from the scratch and for the display image part, here is my code.
let imageURL = NSURL(string: actualCurrentProduct.imageURL)
if let actualImageURL = imageURL {
let imageData = NSData(contentsOfURL: actualImageURL)
if let actualImageData = imageData {
let image = UIImage(data: actualImageData)
if let actualImage = image {
self.productImage.image = actualImage
}
}
}
Finally....

Resources