SDWebImage array url not appearing in uiimageview - swift

I'm using SDWebImage for my Swift. I can't figure out why (frankly, HOW) it's not working. there is no image in imageview.
so this is what i'm trying. parse query PFFile(s) (url converted) stored in a var urlArray:[URL] = []
i have a UIScrollView with UIImageView inside.
in short: query parse - download PFFile URLs to an array (append).
for index in 0..<self.urlArray.count {
var frame = CGRect.zero
frame.origin.x = self.scrollView.frame.size.width * CGFloat(index)
frame.size = self.scrollView.frame.size
self.scrollView.isPagingEnabled = true
let subView = UIImageView(frame: frame)
subView.sd_setImage(with: self.urlArray[index], placeholderImage: #imageLiteral(resourceName: "profile"))
//subView.contentMode = .scaleAspectFit
self.scrollView.addSubview(subView)
}
first url image appears ok. then no pagination & no error (array numbers OK) just nothing apears but first pic. used this : imageview.sd_setImage(with: self.urlArray[index]) is this wrong approach?
thanks

I don't see the code where you update the contentSize of the UIScrollView. Unless you do that, the scroll view won't scroll for you. The additional image views may be there, but hidden outside of the scroll view's current bounds.

sdWebImage is a library using for image caching.
If you wanna detect error for downloading image by sdWebImage then you apply below code and track response from server.
cell.imageView.sd_setImageWithURL(NSURL (string: sendImgUri!), placeholderImage: UIImage (named: "pro.png"), options: .CacheMemoryOnly, progress: { (i, m) in
}, completed: { (image, error, chachType, url) in
if(error != nil)
{
print(error)
}
else if(image != nil)
{
print(image)
}
})

Related

Full Page screenshot of WKWebView for macOS

This is a macOS app, I'm trying to take a full page screenshot of a webview, but i'm unable to get the screenshot of the full page.
Screenshot function.
func takescreenshot(
_ webView: WKWebView,
didFinish navigation: WKNavigation!) {
let configuration = WKSnapshotConfiguration()
configuration.afterScreenUpdates = true
webView.takeSnapshot(with: configuration) { (image, error) in
if let image = image {
//Save Image
}
}
}
from the answers I've seen here the solution seems to be setting the webview scrollview offset, but this is only available for ios. This is the error i get:
Value of type "WKWebView" has no member "scrollView"
I guess the problem is caused by an internal scroll view that optimizes drawing for scrolling - by redrawing only parts that are soon to be visible.
To overcome this, you can temporarily resize the web view to it's full content extent. I know it's not an ideal solution, but you may derive better one based on this idea.
webView.evaluateJavaScript("[document.body.scrollWidth, document.body.scrollHeight];") { result, error in
if let result = result as? NSArray {
let orig = webView.frame
webView.frame = NSRect(x: 0, y: 0, width: (result[0] as! NSNumber).intValue, height: (result[1] as! NSNumber).intValue)
let configuration = WKSnapshotConfiguration()
webView.takeSnapshot(with: configuration) { image, error in
if let image = image {
NSPasteboard.general.clearContents()
NSPasteboard.general.setData(image.tiffRepresentation, forType: .tiff)
}
}
webView.frame = orig
}
}

IMessage MSSticker view created from UIView incorrect sizing

Hey I have been struggling with this for a couple of days now and can't seem to find any documentation out side of the standard grid views for MSStickerView sizes
I am working on an app that creates MSStickerViews dynamically - it does this via converting a UIView into an UIImage saving this to disk then passing the URL to MSSticker before creating the MSStickerView the frame of this is then set to the size of the original view.
The problem I have is that when I drag the MSStickerView into the messages window, the MSStickerView shrinks while being dragged - then when dropped in the messages window, changes to a larger size. I have no idea how to control the size when dragged or the final image size
Heres my code to create an image from a view
extension UIView {
func imageFromView() -> UIImage? {
UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.isOpaque, 0.0)
defer { UIGraphicsEndImageContext() }
if let context = UIGraphicsGetCurrentContext() {
self.layer.render(in: context)
let image = UIGraphicsGetImageFromCurrentImageContext()
return image
}
return nil
}
}
And here's the code to save this to disk
extension UIImage {
func savedPath(name: String) -> URL{
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let filePath = "\(paths[0])/name.png"
let url = URL(fileURLWithPath: filePath)
// Save image.
if let data = self.pngData() {
do {
try data.write(to: url)
} catch let error as NSError {
}
}
return url
}
}
finally here is the code that converts the data path to a Sticker
if let stickerImage = backgroundBox.imageFromView() {
let url = stickerImage.savedPath(name: textBox.text ?? "StickerMCSticker")
if let msSticker = try? MSSticker(contentsOfFileURL: url, localizedDescription: "") {
var newFrame = self.backgroundBox.frame
newFrame.size.width = newFrame.size.width
newFrame.size.height = newFrame.size.height
let stickerView = MSStickerView(frame: newFrame, sticker: msSticker)
self.view.addSubview(stickerView)
print("** sticker frame \(stickerView.frame)")
self.sticker = stickerView
}
}
I wondered first off if there was something I need to do regarding retina sizes, but adding #2x in the file just breaks the image - so am stuck on this - the WWDC sessions seem to show stickers being created from file paths and not altering in size in the transition between drag and drop - any help would be appreciated!
I fixed this issue eventually by getting the frame from the view I was copying's frame then calling sizeToFit()-
init(sticker: MSSticker, size: CGSize) {
let stickerFrame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
self.sticker = MSStickerView(frame: stickerFrame, sticker: sticker)
self.sticker.sizeToFit()
super.init(nibName: nil, bund
as the StickerView was not setting the correct size. Essentially the experience I was seeing was that the sticker size on my view was not accurate with the size of the MSSticker - so the moment the drag was initialized, the real sticker size was implemented (which was different to the frame size / autoLayout I was applying in my view)

How to get image size from image url without downloading in swift

I need image size from URL, When I set image from URL in UITableView
cell, Then I need a frame of UIImage so that I can set UIImageView
Frame size accordingly. I am using below code
cell.imgPostedImage.sd_setImage(with: URL(string: imageArray[0]),placeholderImage: UIImage(named: "placeholder"),options:
SDWebImageOptions(rawValue: 0), completed: { (image, error, cacheType,imageURL) in
print(image?.size.height)
cell.imgPostedImage.setNeedsLayout()
})

NSView dataWithPDF inside rect but with background view

I wan´t to take a screenshot of a NSView but when I do this, I get an image without the background. All the subviews are show, but not the background. I use this code:
if let image = NSImage(data: background.dataWithPDF(inside: background.bounds)) {
let imageView = NSImageView(image: image)
imageView.imageScaling = .scaleProportionallyUpOrDown
return NSImageView(image: image)
}
I thought, ok when I get only the subviews, then I will make a screenshot of the superview and I thried the following:
if let superview = background.superview, let image = NSImage(data: superview.dataWithPDF(inside: background.frame)) {
let imageView = NSImageView(image: image)
imageView.imageScaling = .scaleProportionallyUpOrDown
return NSImageView(image: image)
}
But I get the same result. Even if I set the background color of my background view I don´t get an image without transparent background.
How can I resolve this?
thank you
Artur
I got an Answer:
background.lockFocus()
if let rep = NSBitmapImageRep(focusedViewRect: background.bounds){
let img = NSImage(size: background.bounds.size)
img.addRepresentation(rep)
return NSImageView(image: img)
}
background.unlockFocus()
You could have converted the views backing layer.backgroundColor to an image. Then assign the image to a backing image view that sits in the 0th index of your views heirarchy and use the method dataWithPDF -> that will successfully capture a background.

Why are images from UIImagePickerController sometimes cropped incorrectly?

Sometimes images picked from the photo album with UIImagePickerController are cropped differently than how the user wants to crops it. This happens in approx. 1 of 50 image uploads.
When it happens the images are always cropped to a part of the image from the top left corner. Here is an example image with (1) showing in the red rectangle what the user supposedly selects to crop and (2) what image ends up on the server.
The selection in (1) is assumptive because it's unknown how the users exactly positions the crop and it was not possible to reproduce this incorrect cropping yet. It has only been observed with the live app. Some users tried to upload the same image multiple times always with the same incorrect crop and eventually complained, so it's not that users deliberately crop images like this.
Some users tried to upload different images and all of them were incorrectly cropped.
Here is the code (simplified but nothing more happens to the image):
class ImagePicker {
private let imagePicker = UIImagePickerController()
func showPicker() {
imagePicker.sourceType = .PhotoLibrary
imagePicker.mediaTypes = [kUTTypeImage as String]
imagePicker.allowsEditing = true
imagePicker.delegate = delegate
imagePicker.modalPresentationStyle = .OverFullScreen
parentViewController.presentViewController(imagePicker, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
if let image = info[UIImagePickerControllerEditedImage] as? UIImage {
uploadImage(image)
}
picker.dismissViewControllerAnimated(true, completion: nil)
}
func uploadImage(image: UIImage) {
let imageData = UIImageJPEGRepresentation(image, 0.75)!
let imageFile = PFFile(name: "image.png", data: imageData)
// Upload to Open Source Parse Server which stores the image in an Amazon S3 bucket.
let imageObject = PFObject(className: "ImageClass")
imageObject(imageFile, forKey: "imageFile")
imageObject.saveInBackground()
}
}
Does anyone know why this happens?
Update:
I was able to reproduce the issue on an iPad, I will update here what the outcome was.
Update:
The issue occurred only on iPads so it is presumably related to a bug in the UIImagePickerViewController when cropping an image.
I had the same issue. In my case, i solved it by change content mode of my imageView. It was set to "scaleAspectFill". i just removed it and my image become cropped right way.