Calling a URL within a variable to receive image - ios

I'm trying to grab an image from an URL. Now I know you can do this by using let url = NSURL(string: "http://"). But what if you have a variable that has a url in it.
Example: self.testAd.getImgPath() has http://www.Woods.com/images/imgs/MAU_SouthTrees_mobi.jpg
/as/img.cfm?gphc=14490.
How do we call testAd.getImgPath() to recognize the url and grab the image? I'm using this code below to grab the content and insert it into an image.
let url = NSURL(string:)
var err: NSError?
var imageData :NSData = NSData(contentsOfURL: url!,options: NSDataReadingOptions.DataReadingMappedIfSafe, error: &err)!
var bgImage = UIImage(data:imageData)
imageView.image = bgImage
imageView.contentMode = .ScaleAspectFit

NSURL's initializer, NSURL(string:) takes a string parameter, and it doesn't have to be a literal string. We can pass a string variable in here.
if let url = NSURL(string:testAd.getImgPath()) {
var err: NSError?
if let imageData = NSData(contentsOfURL:url, options:.DataReadingMappedIfSafe, error:&err) {
let bgImage = UIImage(data:imageData)
imageView.image = bgImage
imageView.contentMode = .ScaleAspectFit
}
}

Related

There is an optional error while downloading the image from the storage, I have converted the string to URL

There is an error for optional while downloading the image from the firebase storage, I am converting the string to URL to download the image
here is the code where the error is occuring , if any more code is required do let me know
let imageUrl = URL(string: post._postuserprofileImagUrl)
ImageService.getImage(withURL: imageUrl) { image in
self.profileImageView.image = image
}
You have to (safely) unwrap the URL instance
if let imageUrl = URL(string: post._postuserprofileImagUrl) {
ImageService.getImage(withURL: imageUrl) { image in
self.profileImageView.image = image
}
}
Or even (if postuserprofileImagUrl is optional, too)
if let userprofileImagUrl = post._postuserprofileImagUrl,
let imageUrl = URL(string: userprofileImagUrl) {
ImageService.getImage(withURL: imageUrl) { image in
self.profileImageView.image = image
}
}

Applying Base64 String to UIImageView not working in iOS Swift 2

I have a Base64 string saved from Swift into mysql db. When it comes back, it does not display an image.
How it looks in the db:
LzlqLzRBQVFTa1pKUmdBQkFRQUFTQUJJQUFELzRRQk1SWGhwWmdBQVRVMEFLZ0FBQUFnQUFnRVNBQU1BQUFBQg0KQUFFQUFJZHBBQVFBQUFBQkFBQUFKZ0FBQUFBQUFxQUNBQEZMUlUlJSUUFVVVVVQUZGRkZBQlJSUlFBVVVVVUFGRkZGQUJSUlJRQVVVVVVBRkZGRkFCUlJSUUFVVQ0KVVVBRkZGaWdBcEtXaWdBcEtXaw0Kb0FLS0tLQUNpaWlnQW9vb29BS0tLS0FDaWlpZ0Fvb29vQVNpbG9vQVNpbG9vQVNpaWlnQW9vb29BS0tLS0FDaQ0KaWlnQW9vb29BS0tLS0FDaWlpZ0Fvb29vQUtLS0tB
and this is how I am attempting to receive it but its not working:
let partUrl = "data:image/jpg;base64,";
let appndd = partUrl.stringByAppendingString(baseStringNew!)
let urlWeb = appndd
let requestURL: NSURL = NSURL(string: urlWeb)!
let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(urlRequest) {
(data, response, error) -> Void in
if error == nil {
NSLog("Success!")
dispatch_async(dispatch_get_main_queue(), {
imageNewView.layer.cornerRadius = 10.0
imageNewView.clipsToBounds = true
// Adding a border to the image profile
imageNewView.layer.borderWidth = 1.0
imageNewView.layer.borderColor = UIColor.grayColor().CGColor
imageNewView.image = UIImage(data:data!)
})
} else {
NSLog("Fail")
}
} //end of task
task.resume()
This displays a blank image in the UIImageView. How do I get this string to show up as an image?
Make sure that you prepend your data with data:image/png;base64.
Here is an q&a about this, How to display a base64 image within a UIImageView?
You might want to check the base64 string you stored and retrieved from your MySQL DB. Try using BLOB data type.
Then converting base64 string to NSData then UIImage is pretty easy and straightforward.
let rawData = NSData.init(contentsOfURL: NSURL(string: "http://cdn.sstatic.net/stackoverflow/company/img/logos/so/so-logo.png")!)!
let base64String = rawData.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
let imageData = NSData(base64EncodedString: base64String, options: .IgnoreUnknownCharacters)
let image = UIImage(data: imageData!)

Retrieving saved image using swift

I am trying to retrieve an image saved using:
let pngData = UIImagePNGRepresentation(image)
let finalPath = filePath() // This method just create the path to save to.
saveImage(pngData, filePath: finalPath)
Later I want to retrieve this data and set the UIImageView of a UIButton. However when I use the following code, it just displays a completely blue image.
Here is the code:
let filePath = tempCard?.frontPhoto
let imgData = UIImage(contentsOfFile: filePath!)frontPhotoButton.setImage(imgData, forState: .Normal)
frontPhotoButton.setImage(imgData, forState: .Normal)
I am not sure why this is just showing a blue button.
Edit:
I have also tried:
let filePath = tempCard?.frontPhoto
let imageData = NSData(contentsOfFile: filePath!
let image = UIImage(data: imageData!)
frontPhotoButton.setImage(image, forState: .Normal)
Same result.
For anyone else who has a problem in the future setting the background image of a UIButton. Both of the above code snippets work to retrieve the image.
The Problem was, in interface builder my button was: Type - System. When I changed Type - Custom everything worked fine.
Use this method to retrieve image from document directory of an app
func loadImageFromPath() {
dispatch_async(dispatch_get_main_queue(), {
let fileManager = NSFileManager.defaultManager()
var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
var getImagePath = paths.stringByAppendingPathComponent("Image2.png")
if (fileManager.fileExistsAtPath(getImagePath))
{
println("FILE AVAILABLE AT \(paths)");
//Pick Image and Use accordingly
var imageis: UIImage = UIImage(contentsOfFile: getImagePath)!
let data: NSData = UIImagePNGRepresentation(imageis)
self.imgProfileView.image = UIImage(data: data)
self.imgProfileView.contentMode = UIViewContentMode.ScaleAspectFit
}
else
{
println("FILE NOT AVAILABLE");
}
});
}

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....

impossible to build a dynamic NSURL to put images in UIImage

I try to display dynamic image.
image I receive in my json stream is "http / mySite.com / image.jpg"
So I created a var imageURL: UIImageView! in my class and I have a method that I fulfill my scrollview, in this method I this piece of code that does not work and I do not know what I've forgotten:Here the error of this line: URLWithString 'is unavailable: use object building' NSURL (string :)'
var imageURL: NSURL = NSURL.URLWithString(picture)
Here is the full code
self.imageURL = UIImageView()
self.imageURL.frame.origin.y = 50
var picture = subJson["pagemap"]["cse_thumbnail"][0]["src"].stringValue
var imageURL: NSURL = NSURL.URLWithString(picture)
var imageData: NSData = NSData(contentsOfURL: imageURL)!
var image: UIImage = UIImage(data: imageData)!
self.imageURL.image = UIImage(image)
thanks
Do what the error tells you to do.
Instead of: var imageURL = NSURL.URLWithSting(picture)
do: var imageURL = NSURL(string: picture)

Resources