how to download an image in OS X using swift language - macos

I have created a button for OSX in Swift language. I wish that button should download an image in my Mac.
What code should I use for downloading that image?
Following is the code that I used:
#IBAction func buttonPressed(sender: NSButton) {
buttonPresses+=1
theLabel.stringValue = "You've pressed the button \n \(buttonPresses) times!"
theButton.title = "Download\(buttonPresses)"
}

Alamofire is an easy way to download an image:
Alamofire.request(.GET, url).response() { request, response, data, error in
var image: UIImage?
if nil == error {
if let imageData = data as? NSData {
image = UIImage(data: imageData)
}
}
self.imageView.image = image
}

Related

SwiftUI: Image with barcode doesn't show up

I'm trying to present an instance of UIImage, generated as a barcode from a string:
if let image = UIImage(barcode: "1234567890") {
Image(uiImage: image)
}
But it shows empty rectangle, though in debug the image is populated with the real image:
I use a simple UIImage extension to generate an UIImage with barcode from a string:
extension UIImage {
convenience init?(barcode: String) {
let data = barcode.data(using: .ascii)
guard let filter = CIFilter(name: "CICode128BarcodeGenerator") else {
return nil
}
filter.setValue(data, forKey: "inputMessage")
guard let ciImage = filter.outputImage else {
return nil
}
self.init(ciImage: ciImage)
}
}
What's wrong? Any ideas?
Yes, looks like some defect/incompatibility with Image. You can file a feedback to Apple.
Meanwhile here is a workaround. Tested with Xcode 12 / iOS 14
struct TestBarCodeView: View {
var body: some View {
VStack {
BarCodeView(barcode: "1234567890")
.scaledToFit()
.padding().border(Color.red)
}
}
}
struct BarCodeView: UIViewRepresentable {
let barcode: String
func makeUIView(context: Context) -> UIImageView {
UIImageView()
}
func updateUIView(_ uiView: UIImageView, context: Context) {
uiView.image = UIImage(barcode: barcode)
}
}

Xcode - how to display image from url

I am able to display image from the sources, but was wondering how to display image from the URL link:
ccell.avatarImageView.image= [UIImage imageNamed:#"home_new.png"];
Thanks for the help.
Add this outside of the class scope:
import UIKit
extension UIImageView {
func loadurl(url: URL) {
DispatchQueue.global().async { [weak self] in
if let data = try? Data(contentsOf: url) {
if let image = UIImage(data: data) {
DispatchQueue.main.async {
self?.image = image
}
}
}
}
}
}
Then add this to wherever you're trying to load your image:
let urlYourURL = URL (string: #"home_new.png")
avatarImageView.loadurl(url: urlYourURL!)
Download the image as data from URL using NSURLConnection and use below code
let imageView:UIImageView = UIImageView.init(image: UIImage.init(data: **data**, scale: 1.0));

Swift2 retrieving images from Firebase

I am trying to read/display an image from Firebase. I am first encoding the image and then posting this encoded String to Firebase. This runs fine. When I try and decode the encoded string from Firebase and convert it to an image, I am getting a nil value exception.
This is how I am saving the image to Firebase
var base64String: NSString!
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
self.dismissViewControllerAnimated(true, completion: nil)
imageToPost.image = image
var uploadImage = image as! UIImage
var imageData = UIImagePNGRepresentation(uploadImage)!
self.base64String = imageData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
let ref = Firebase(url: "https://XXX.firebaseio.com")
var quoteString = ["string": self.base64String]
var usersRef = ref.childByAppendingPath("goalImages")
var users = ["image": quoteString]
usersRef.setValue(users)
displayAlert("Image Posted", message: "Your image has been successfully posted!")
}
This is how I am trying to read the image from Firebase
// ViewController.swift
import UIKit
import Firebase
class ViewController: UIViewController {
#IBOutlet weak var image: UIImageView!
var base64String: NSString!
#IBAction func buttonClicked(sender: AnyObject) {
sender.setTitle("\(sender.tag)", forState: UIControlState.Normal)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let ref = Firebase(url: "https://XXX.firebaseio.com/goalImages/image/string")
ref.observeEventType(.Value, withBlock: { snapshot in
self.base64String = snapshot.value as! NSString
let decodedData = NSData(base64EncodedString: self.base64String as String, options: NSDataBase64DecodingOptions())
//Next line is giving the error
var decodedImage = UIImage(data: decodedData!)
self.image.image = decodedImage
}, withCancelBlock: { error in
print(error.description)
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
The error says: "fatal error: unexpectedly found nil while unwrapping an Optional value"; decodedData is nil. Could someone explain what is going wrong.
Instead of
let decodedData = NSData(base64EncodedString: self.base64String as String,
options: NSDataBase64DecodingOptions())
try adding IgnoreUnknownCharacters
NSDataBase64DecodingOptions.IgnoreUnknownCharacters
Use Example: Encode a jpg, store and read from firebase
encode and write our favorite starship
if let image = NSImage(named:"Enterprise.jpeg") {
let imageData = image.TIFFRepresentation
let base64String = imageData!.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
let imageRef = myRootRef.childByAppendingPath("image_path")
imageRef.setValue(base64String)
read and decode
imageRef.observeEventType(.Value, withBlock: { snapshot in
let base64EncodedString = snapshot.value
let imageData = NSData(base64EncodedString: base64EncodedString as! String,
options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters)
let decodedImage = NSImage(data:imageData!)
self.myImageView.image = decodedImage
}, withCancelBlock: { error in
print(error.description)
})
EDIT 2019_05_17
Update to Swift 5 and Firebase 6
func writeImage() {
if let image = NSImage(named:"Enterprise.jpg") {
let imageData = image.tiffRepresentation
if let base64String = imageData?.base64EncodedString() {
let imageRef = self.ref.child("image_path")
imageRef.setValue(base64String)
}
}
}
func readImage() {
let imageRef = self.ref.child("image_path")
imageRef.observeSingleEvent(of: .value, with: { snapshot in
let base64EncodedString = snapshot.value as! String
let imageData = Data(base64Encoded: base64EncodedString, options: Data.Base64DecodingOptions.ignoreUnknownCharacters)!
let decodedImage = NSImage(data: imageData)
self.myImageView.image = decodedImage
})
}
Firebase Engineer here:
I highly recommend using the new Firebase Storage API for uploading images to Firebase. It's simple to use, low cost, and backed by Google Cloud Storage for huge scale.
You can upload from NSData or an NSURL pointing to a local file (I'll show NSData, but the principle is the same):
// Data in memory
let data: NSData = ...
// Create a reference to the file you want to upload
let riversRef = storageRef.child("images/rivers.jpg")
// Upload the file to the path "images/rivers.jpg"
let uploadTask = riversRef.putData(data, metadata: nil) { metadata, error in
if (error != nil) {
// Uh-oh, an error occurred!
} else {
// Metadata contains file metadata such as size, content-type, and download URL.
let downloadURL = metadata!.downloadURL
// This can be stored in the Firebase Realtime Database
// It can also be used by image loading libraries like SDWebImage
}
}
You can even pause and resume uploads, and you can easily monitor uploads for progress:
// Upload data
let uploadTask = storageRef.putData(...)
// Add a progress observer to an upload task
uploadTask.observeStatus(.Progress) { snapshot in
// Upload reported progress
if let progress = snapshot.progress {
let percentComplete = 100.0 * Double(progress.completedUnitCount) / Double(progress.totalUnitCount)
}
}

fatal error: unexpectedly found nil while unwrapping an Optional value in Swift 2

My app works fine on the simulator but crashes with this message running it on iPhone device. Why and how can I fix it?
How can I find on what code line the app crashes?
func playButton(playButton: UIButton!) {
var image = UIImage()
if activePlayer == 1 { image = UIImage(named: "x.png")! }
else { image = UIImage(named: "o.png")! }
playButton.setImage(image, forState: .Normal)
}
In the code you show, the part where it could generate this error is probably the forced unwrapped UIImage. Modify your code like this to find out:
func playButton(playButton: UIButton!) {
let imageName: String
if activePlayer == 1 {
imageName = "x.png"
} else {
imageName = "o.png"
}
if let image = UIImage(named: imageName) {
playButton.setImage(image, forState: .Normal)
} else {
print("error while retrieving image named '\(imageName)'")
}
}
The IOS device is case sensitive while the simulator isn't. So, I replaced the image names to the exact file names ("X.png" and "O.png" instead of "x.png" and "o.png"). Now, UIImage(named: "X.png") is not nil and the app works fine.
Here, we would use if let and have a look at below
func playButton(playButton: UIButton!) {
var image = UIImage()
if let player = activePlayer {
if player == 1 {
image = UIImage(named: "x.png")! }
} else { image = UIImage(named: "o.png")! }
playButton.setImage(image, forState: .Normal)
}
(or) if you are using Swift 2.0 and Xcode 7, guard is good choice too.

Downloading Image Swift

I want to download an image from Facebook and store it to my cache, which I call over HTTPS. If I just use HTTP everything works fine, but if I change it to HTTPS it does not work anymore.
Here is my code:
// Grab the artworkUrl key to get an image URL for thumbnail
var urlString: NSString = rowData["cover"] as NSString
// Check our image cache for the existing key. This is just a dictionary of UIImages
var image: UIImage? = self.imageCache.valueForKey(urlString) as? UIImage
if( !image? ) {
// If the image does not exist, we need to download it
var imgURL: NSURL = NSURL(string: urlString)
// Download an NSData representation of the image at the URL
var request: NSURLRequest = NSURLRequest(URL: imgURL)
var urlConnection: NSURLConnection = NSURLConnection(request: request, delegate: self)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse!,data: NSData!,error: NSError!) -> Void in
if !error? {
//var imgData: NSData = NSData(contentsOfURL: imgURL)
image = UIImage(data: data)
// Store the image in to our cache
self.imageCache.setValue(image, forKey: urlString)
cell.image = image
println(self.imageCache)
}
else {
println("Error: \(error.localizedDescription)")
}
})
}
else {
cell.image = image
}
})
The URL I want to use is this:
https://fbcdn-sphotos-d-a.akamaihd.net/hphotos-ak-xpf1/t1.0-9/q71/s720x720/995054_485489274919674_7207866955460529362_n.jpg
The Error is a "Timeout".
With this URL everything works fine:
http://fbcdn-sphotos-d-a.akamaihd.net/hphotos-ak-xpf1/t1.0-9/q71/s720x720/995054_485489274919674_7207866955460529362_n.jpg
Thanks,
Tobias
From what I can tell NSURLConnection sometimes runs into trouble with HTTPS connections. Try adding these two methods to your class (and mark it as NSURLConnectionDelegate) (from this answer):
func connection(connection: NSURLConnection!, canAuthenticateAgainstProtectionSpace protectionSpace: NSURLProtectionSpace!) -> Bool {
return true
}
func connection(connection: NSURLConnection!, didReceiveAuthenticationChallenge challenge: NSURLAuthenticationChallenge!) {
challenge.sender.useCredential(NSURLCredential(forTrust: challenge.protectionSpace.serverTrust), forAuthenticationChallenge: challenge)
}

Resources