Kingfisher and swift 3 - cannot set image with url - swift3

Checking the documentation and the migration guide, I should be able to set a new image using this code:
imageView.kf.setImage(with:url ...)
but actually I cannot find this method in the library, I only see:
imageView.kf.setImage(with:Resource... )
I don't know exactly how this resource shoud work though since I cannot find anything in the documentation.

Resource is a protocol. URL has been extended to conform to this protocol. So you can do:
let url = URL(string: ...)!
imageView.kf.setImage(with: url)
If you want some control over what Kingfisher uses for the key in its cache, you can use ImageResource:
let identifier = "..."
let url = URL(string: "http://example.com/images/identifier=\(identifier)")!
let resource = ImageResource(downloadURL: url, cacheKey: identifier)
imageView.kf.setImage(with: resource)

For Swift 4.2
import Kingfisher
extension UIImageView {
func setImage(with urlString: String){
guard let url = URL.init(string: urlString) else {
return
}
let resource = ImageResource(downloadURL: url, cacheKey: urlString)
var kf = self.kf
kf.indicatorType = .activity
self.kf.setImage(with: resource)
}
}
How to use
self.imgVw.setImage(with: your image url)

I fixed that issue using this:
PhotoHelper.shared.imagePickedBlock = { [weak self] (image, url) in
self?.imageView.kf.setImage(with: url, placeholder: image, options: nil, progressBlock: nil, completionHandler: { imageResult, error, type, cache in
self?.imageView.image = image
})
}
PhotoHelper is wrapper on native Image Picker:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
currentVC.dismiss(animated: true, completion: {
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
let url = info[UIImagePickerControllerReferenceURL] as! URL
self.imagePickedBlock?(image, url)
}
})
}

Related

Dismiss share extension from custom SwiftUI view

I am using custom SwiftUI view from main target for sharing document from ShareViewController of share extension. Using Navigation link and sharing the document after navigating through three views. document is uploaded without any problem, but I don't know how to close the views after upload is done.
This is how navigation looks like
ShareViewController(SLComposeServiceViewController) -> PropertyListView -> UnitListView -> UploadView
and didPost looks like this
override func didSelectPost() {
print("In Did Post")
if let item = self.extensionContext?.inputItems[0] as? NSExtensionItem{
print("Item \(item)")
print(item.attachments)
print(item.attachments![0])
let itemProvider = item.attachments![0]
if itemProvider.hasItemConformingToTypeIdentifier("com.adobe.pdf"){
itemProvider.loadItem(forTypeIdentifier: "com.adobe.pdf", options: nil) { (item, error) in
if error != nil{
print(error!.localizedDescription)
}else{
if let url = item as? URL{
print(url)
DispatchQueue.main.async{
//saving to user defaults
let dict: [String : Any] = ["dcument" : url.absoluteString, "name" : self.contentText.isEmpty ? url.lastPathComponent : self.contentText!]
let savedata = UserDefaults.init(suiteName:"group.in.pixbit.hijricalendar")
savedata?.set(dict, forKey: "sharedDocument")
savedata?.synchronize()
//loading swiftui view
let swiftuiView = NavigationView{PropertyListView()}
let vc = UIHostingController(rootView: swiftuiView)
let newView = vc
self.view.window?.rootViewController = newView
self.view.window?.makeKeyAndVisible()
}
}
}
}
}
}
}
You need to call completeRequest(returningItems:completionHandler:) on the extensionContext of your view controller.
Here is a code snippet from one of my apps:
override func didSelectPost() {
let artifact = Artifact(title: self.contentText,
author: self.metaAuthor,
url: url?.absoluteString ?? metaUrl ?? "",
imageUrl: metaImage,
siteName: self.siteName,
dateAdded: Date(),
excerpt: metaDescription,
notes: "",
tags: nil)
self.artifactRepository?.addArtifact(artifact)
self.extensionContext?.completeRequest(returningItems: [], completionHandler:nil)
}

How to play video with cookies content in iOS using AVPlayer in Swift?

I have used the below implementation to play a video with cookies content from the server, but it shows play icon with cross line. I have refer the link and do following implementation in swift. but I didn't get any output :(
func showVideo(url: String) {
let videoURL = NSURL(string: url)
var cookiesArray = [HTTPCookie]()
guard let cookieArray = UserDefaults.standard.array(forKey:
Constants.Object.kCookie) as? [[HTTPCookiePropertyKey: Any]] else {
return }
for cookieProperties in cookieArray {
if let cookie = HTTPCookie(properties: cookieProperties) {
cookiesArray.append(cookie)
}
}
let cookieArrayOptions = [AVURLAssetHTTPCookiesKey: cookiesArray]
let assets = AVURLAsset(url: videoURL! as URL, options: cookieArrayOptions)
let item = AVPlayerItem(asset: assets)
videoPlayer = AVPlayer(playerItem: item)
self.playerController.player = self.videoPlayer
self.playerController.view.frame = self.view.frame
self.present(self.playerController, animated: true, completion: nil)
self.playerController.player?.play()
}
Please help me on that, what is wrong in that implementation.
Thanks in advance! :)
After going through so many ways finally I have got the solution which worked for me :
func showVideo(url: String) {
let videoURL = NSURL(string: url)
let cookiesArray = HTTPCookieStorage.shared.cookies! //Stored Cookies of your request
let values = HTTPCookie.requestHeaderFields(with: cookiesArray)// Returns a dictionary of header fields corresponding to a provided array of cookies.ex.["Cookie":"your cookies values"]
let cookieArrayOptions = ["AVURLAssetHTTPHeaderFieldsKey": values]
let assets = AVURLAsset(url: videoURL! as URL, options: cookieArrayOptions)
let item = AVPlayerItem(asset: assets)
videoPlayer = AVPlayer(playerItem: item)
self.playerController.player = self.videoPlayer
self.playerController.view.frame = self.view.frame
self.present(self.playerController, animated: true, completion: nil)
self.playerController.player?.play()
}

Fetch video from server through API using AVPlayer in Swift 3

I am trying to fetch video from server in AVPlayer.The data is in JSON format. I have given down data of JSON format too. The video is in .mp4 format.
But the video doesn't play. But before I tried to play the video from local storage of .mp4, it played successfully in AVPlayer. What is problem with my code? I am using Swift 3.
My code is :
//ViewController
import UIKit
import AVFoundation
import AVKit
import Alamofire
class ViewController: UIViewController {
var playerController = AVPlayerViewController()
var player:AVPlayer?
var playerController1 = AVPlayerViewController()
var player1:AVPlayer?
var dictDataImage:NSArray = NSArray()
var dictDataVideo: NSArray = NSArray()
var appDictionary:NSDictionary!
#IBOutlet var videoPreviewLayer2: YTPlayerView!
override func viewDidLoad() {
super.viewDidLoad()
self.videos()
videoPreviewLayer2.delegate = self
}
func videos(){
let collectionviewone: String = "http://rillmark.academy/api/rillmark-academy/home-page-video"
Alamofire.request(collectionviewone, method: .get, parameters: nil, encoding: JSONEncoding.default)
.responseJSON { response in
debugPrint(response.result)
if let JSON = response.result.value{
self.appDictionary = (JSON as AnyObject) as! NSDictionary
print("self.app =",self.appDictionary)
let url1: URL = URL(string: (self.appDictionary.value(forKey: "home_video")) as! String)!
let url4 = url1.absoluteString
print("url11=", url1)
print("url22=", url4)
let url3 = NSURL(fileURLWithPath: url4)
let item = AVPlayerItem(url: url3 as URL)
print("item=", item)
self.player = AVPlayer(playerItem: item)
self.playerController = AVPlayerViewController()
self.playerController.player = self.player
self.playerController.view.frame = self.videoPreviewLayer.frame
self.videoPreviewLayer.addSubview(self.playerController.view)
self.playerController.showsPlaybackControls = false
self.playerController.player?.play()
}
}
}
}
//JSON
{
"status": "Success",
"home_video": "http://video/homepage/e27U0B_1502445369-homepage-2.mp4",
}

Swift 3, want to perform timeout when using URLSession to load image from server

I'm using swift 3. I want to add timeout to URLSession when doing download task. I did use configuration to change my setting, however, it doesn't work. The code didn't perform timeout... If the server didn't response quickly, it will fail.
Here is my code:
import Foundation
import UIKit
extension UIImageView {
func loadImage(url: URL) -> URLSessionDownloadTask {
let session: URLSession = {
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForRequest = 70
configuration.timeoutIntervalForResource = 70
return URLSession(configuration: configuration, delegate: nil, delegateQueue: nil)
}()
let downloadTask = session.downloadTask(with: url, completionHandler: { [weak self] url, response, error in
if error == nil, let url = url, let data = try? Data(contentsOf: url), let image = UIImage(data: data) {
DispatchQueue.main.async {
if let strongSelf = self {
strongSelf.image = image
}
}
}
})
downloadTask.resume()
return downloadTask
}
}
Any comment is appreciated!!

Swift 3 - Download JPEG image and save to file - macOS

I have a downloader class that downloads a file based on a given URL which then calls a completion passing it the contents of the file as NSData.
For the project that I'm using this in, the URL will be a JPEG image. The downloader works perfectly; I can use the result into NSImage and show it in a Image View Controller.
I would like to be able to save that NSData object to file.
After quite some time researching the internet on Google, StackOverflow, etc. and trying many suggestions, I cannot get the file to save.
Here is a playground of the Downloader class and my attempt to save the file:
//: Playground - noun: a place where people can play
import Cocoa
class NetworkService
{
lazy var configuration: URLSessionConfiguration = URLSessionConfiguration.default
lazy var session: URLSession = URLSession(configuration: self.configuration)
let url: NSURL
init(url: NSURL)
{
self.url = url
}
func downloadImage(completion: #escaping ((NSData) -> Void))
{
let request = NSURLRequest(url: self.url as URL)
let dataTask = session.dataTask(with: request as URLRequest) { (data, response, error) in
if error == nil {
if let httpResponse = response as? HTTPURLResponse {
switch (httpResponse.statusCode) {
case 200:
if let data = data {
completion(data as NSData)
}
default:
print(httpResponse.statusCode)
}
}
} else {
print("Error download data: \(error?.localizedDescription)")
}
}
dataTask.resume()
}
}
let IMAGE_URL = NSURL(string: "https://www.bing.com/az/hprichbg/rb/RossFountain_EN-AU11490955168_1920x1080.jpg")
let networkService = NetworkService(url: IMAGE_URL!)
networkService.downloadImage(completion: { (data) in
data.write(to: URL(string: "file://~/Pictures/image.jpg")!, atomically: false)
})
The playground console show nothing at all. Can anyone spot why its not working?
NOTE: The target is macOS, not iOS. Also, I'm a swift noob...
I did try this:
networkService.downloadImage(completion: { (imageData) in
let imageAsNSImage = NSImage(data: imageData as Data)
if let bits = imageAsNSImage?.representations.first as? NSBitmapImageRep {
let outputData = bits.representation(using: .JPEG, properties: [:])
do {
try outputData?.write(to: URL(string: "file://~/Pictures/myImage.jpg")!)
} catch {
print("ERROR!")
}
}
})
It could be a permission issue. You may try:
let picturesDirectory = FileManager.default.urls(for: .picturesDirectory, in: .userDomainMask)[0]
let imageUrl = picturesDirectory.appendingPathComponent("image.jpg", isDirectory: false)
try? data.write(to: imageUrl)
It does work for me: