let url = URL(string: "http://i.imgur.com/w5rkSIj.jpg")
let data = try? Data(contentsOf: url)
if let imageData = data {
let image = UIImage(data: imageData)
}
I am trying to do the above for loading an image from url but when i type the Data(contentsOf: url) line i get an error saying "Argument passed to call that takes no argumens". What may be causing this? NSData(contentsOf: url) works but i need the Data one
url is optional variable so use optional binding
guard let url = URL(string: "http://i.imgur.com/w5rkSIj.jpg") else {
return
}
let data = try? Data(contentsOf: url)
if let imageData = data {
let image = UIImage(data: imageData)
}
Related
This question already has answers here:
Loading/Downloading image from URL on Swift
(39 answers)
Closed 3 years ago.
I am trying to load image from url in my ios app swift. I have written following code.
let imageURL = minHost + "\(userData["profileImage"])"
let url = URL(string: imageURL)!
let imageData = try? Data(contentsOf: url)
profileImage.image = UIImage(data: imageData!)
Now imageURL is having proper url, but imageData receives nil and because of this, last line through an error Fatal error: Unexpectedly found nil while unwrapping an Optional value
Instead of fetching image using Data(contentsOf:) method, use URLSession to perform network calls.
let imageURL = minHost + "\(userData["profileImage"])"
if let url = URL(string: imageURL) {
URLSession.shared.dataTask(with: url) {[weak self] (data, urlResponse, error) in
if let data = data {
DispatchQueue.main.async {
self?.profileImage.image = UIImage(data: imageData)
}
}
}.resume()
}
Important Note: Avoid using forced unwrapping (!) unnecessarily. It might result in unwanted app crashes. Instead use guard or if-let to unwrap optionals.
Try this at Playground.
Loading image from the URL takes some time, and need to be executed at another Thread, different from the main thread.
import UIKit
let url = URL(string: "https://cdn.arstechnica.net/wp-content/uploads/2018/06/macOS-Mojave-Dynamic-Wallpaper-transition.jpg")!
var image = UIImage()
DispatchQueue.global().async {
if let data = try? Data(contentsOf: url) {
DispatchQueue.main.async {
image = UIImage(data: data)!
}
}
}
image
you can try like this:
let url = URL(string: "image url here")
if url != nil {
DispatchQueue.global().async { [weak self] in
if let data = try? Data(contentsOf: url!) {
if let image = UIImage(data: data) {
DispatchQueue.main.async {
self.profileImage.image = image
}
}
}
}
}
Try This
let url = URL(string:imageURL)
if let data = try? Data(contentsOf: url!)
{
profileImage.image = UIImage(data: data, scale: 1.0)!
}
Never do the downloading task on main thread. if you do, you will not able to access components in current visible screens properly. It should be always on the background thread.
if let url = URL(string: "https://....") {
DispatchQueue.global(qos: .background).async {
if let data = try? Data(contentsOf: url) {
if let image = UIImage(data: data) {
DispatchQueue.main.async {
self.profileImage.image = image
}
}
}
}
}
This problems it's driving me crazy...
I have this string url:
"verona-api.municipiumstaging.it/system/images/image/image/22/app_1920_1280_4.jpg"
and I have to load this image in my imageView.
this is my code :
do {
let url = URL(fileURLWithPath: "http://verona-api.municipiumstaging.it/system/images/image/image/22/app_1920_1280_4.jpg")
let data = try Data(contentsOf: url)
self.imageView.image = UIImage(data: data)
}
catch{
print(error)
}
This throw the exception :
No such file or directory.
But if I search this url with a browser I can see the image correctly!
You are using wrong method to create URL. Try URLWithString instead of fileURLWithPath. fileURLWithPath is used to get image from local file path not from internet url.
or
do {
let url = URL(string: "http://verona-api.municipiumstaging.it/system/images/image/image/22/app_1920_1280_4.jpg")
let data = try Data(contentsOf: url)
self.imageView.image = UIImage(data: data)
}
catch{
print(error)
}
The method fileURLWithPath opens file from file system. The file address is prepended with file://. You can print the url string.
From Apple documentation about + (NSURL *)fileURLWithPath:(NSString *)path;
The path that the NSURL object will represent. path should be a valid
system path, and must not be an empty path. If path begins with a
tilde, it must first be expanded with stringByExpandingTildeInPath. If
path is a relative path, it is treated as being relative to the
current working directory.
Here is one of a few possible solutions:
let imageName = "http://verona-api.municipiumstaging.it/system/images/image/image/22/app_1920_1280_4.jpg"
func loadImage(with address: String) {
// Perform on background thread
DispatchQueue.global().async {
// Create url from string address
guard let url = URL(string: address) else {
return
}
// Create data from url (You can handle exeption with try-catch)
guard let data = try? Data(contentsOf: url) else {
return
}
// Create image from data
guard let image = UIImage(data: data) else {
return
}
// Perform on UI thread
DispatchQueue.main.async {
let imageView = UIImageView(image: image)
/* Do some stuff with your imageView */
}
}
}
loadImage(with: imageName)
It's best practice if you just send a completion handler to perform on main thread to loadImage(with:).
Here the url is not of the local system but of the server.
let url = URL(fileURLWithPath: "http://verona-api.municipiumstaging.it/system/images/image/image/22/app_1920_1280_4.jpg")
Here the url created is of file which is locally on the device.
Create url like this:-
url = URL(string: "http://verona-api.municipiumstaging.it/system/images/image/image/22/app_1920_1280_4.jpg")
Use below code snippet to loading an image into imageview
func imageDownloading() {
DispatchQueue.global().async {
let url = URL(string: "http://verona-api.municipiumstaging.it/system/images/image/image/22/app_1920_1280_4.jpg")!
do {
let data = try Data(contentsOf: url)
DispatchQueue.main.async {
self.imageView.image = UIImage(data: data)
}
} catch {
print(error.localizedDescription)
}
}
}
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 {
}
}
I'm trying to convert NSURL to NSData. My url string is a local file url which I'm getting from my device.
let url = NSURL(string: url)
let imageData = NSData(contentsOfURL: url)
let image = UIImage(data: imageData)
I'm getting NSURL value properly. But while converting it to NSData it gives nil value. I know there are similar questions in stackoverflow but none of them solves my problem. I'm using swift 2.2
If the string points to a local file url then you are using the wrong API. The correct one is
let url = NSURL(fileURLWithPath: urlString)
NSURL(string: is only for URL strings which start with a valid file scheme (e.g. http or ftp)
Try this code.
let urlString = "/var/mobile/Media/DCIM/101APPLE/IMG_1827.JPG"
let url = URL(fileURLWithPath: urlString)
let imageData = NSData(contentsOf: url)
let image = UIImage(data: imageData as! Data)
The Correct one is use contentsOf: forecastURL! as URL instead of contentsOf: forecastURL
let forecastURL = NSURL(string: "http://photos.state.gov/libraries/media/788/images/90x90.gif")
let testImage = NSData (contentsOf: forecastURL! as URL)
print("data",testImage!)
let image = UIImage(data: testImage! as Data)
print("imaGE :-",image!)
I am using NSUrlconnection to call to api but now i have also receive image from api so i don't know how to load the image & save into phones local memory because these images are further using in app . please help me. how to use & show image from local save.I am using below function to load the image but NSURLSession.sharedSession() are not going to inside the queue.
func saveImage(url:NSString,image_name1:NSString)
{
NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: url as String)!, completionHandler: { (data, response, error) -> Void in
if error != nil {
print(error)
return
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let image = UIImage(data: data!)
var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
let documentsDirectory = paths[0]
let path = NSURL(fileURLWithPath: documentsDirectory).URLByAppendingPathComponent(image_name1 as String)!.absoluteString
print(" file path is \(path)")
let data = UIImagePNGRepresentation(image!)
data!.writeToFile(path!, atomically: true)
})
}).resume()
}
for save
var image = .... // However you create/get a UIImage
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let destinationPath = documentsPath.stringByAppendingPathComponent("filename.jpg")
UIImageJPEGRepresentation(image,1.0).writeToFile(destinationPath, atomically: true)
for cash
https://github.com/onevcat/Kingfisher
pod 'Kingfisher'
let url = URL(string: "url_of_your_image")
imageView.kf.setImage(with: url)
it's automatic cash images
Try this :
let data = try? Data(contentsOf: url!) //make sure your image in this url does exist, otherwise unwrap in a if let check / try-catch
imageView.image = UIImage(data: data!)
From : https://stackoverflow.com/a/27517280/3901620