gpt4 book ai didi

ios - Swift:拖放,保存来自谷歌图像的图像网址

转载 作者:行者123 更新时间:2023-11-29 05:14:32 25 4
gpt4 key购买 nike

我正在尝试创建一个由 Collection View 组成的应用程序,其中将图像拖到其上。

我正在双显示器中打开谷歌图像,搜索“密封件”并将密封件的第一张图像拖到我的应用程序的 View Controller 上。我的应用程序应该保存图像的网址。 Collection View 中的每个单元格都会从保存的 url 中获得一个 url。设置 url 后,单元格会从 url 检索图像并将图像放置在自身内部。

问题是采用了错误的网址。获取的 url 可以转换为数据,但该数据无法转换为 UIImage。拖放保存的网址不是图像的网址,它似乎是谷歌搜索或其他东西的网址。

我需要能够保存图像的正确网址,以便 ImageCell 可以从该网址加载图像。


当我在网络浏览器中输入网址时,我会收到这样的页面。

enter image description here

ImageViewController

import UIKit

class ImageViewController: UIViewController{

@IBOutlet weak var collectionView: UICollectionView!

override func viewDidLoad() {
super.viewDidLoad()
}

var gallery = [URL]()

}

extension ImageViewController: UICollectionViewDelegate, UICollectionViewDataSource{

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return gallery.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCell", for: indexPath) as! ImageCell
cell.url = gallery[indexPath.item]
return cell
}
}

extension ImageViewController: UICollectionViewDropDelegate{

func collectionView(_ collectionView: UICollectionView, canHandle session: UIDropSession) -> Bool {
return session.canLoadObjects(ofClass: NSURL.self) && session.canLoadObjects(ofClass: UIImage.self)
}

func collectionView(_ collectionView: UICollectionView, dropSessionDidUpdate session: UIDropSession, withDestinationIndexPath destinationIndexPath: IndexPath?) -> UICollectionViewDropProposal {
return UICollectionViewDropProposal(operation: .copy)
}

func collectionView(_ collectionView: UICollectionView, performDropWith coordinator: UICollectionViewDropCoordinator) {

// Get the destion index path, if there's none set, just insert at the beginning
let destinationIndexPath = coordinator.destinationIndexPath ?? IndexPath(item: 0, section: 0)

// Process all items being dragged
for item in coordinator.items {

// External drops must provide url and an image that we'll use to get an aspect-ratio
var url: URL?

// Get the URL
item.dragItem.itemProvider.loadObject(ofClass: NSURL.self) { [weak self] (provider, error) in

url = provider as? URL //Check that url is valid

// If both url and ratio were provided, perform the actual drop
if url != nil{
DispatchQueue.main.async {
collectionView.performBatchUpdates({
// Update model
self?.gallery.insert(url!, at: destinationIndexPath.item)

// Update view
collectionView.insertItems(at: [destinationIndexPath])

// Animates the item to the specified index path in the collection view.
coordinator.drop(item.dragItem, toItemAt: destinationIndexPath)
})
}
}
}
}

}

}

ImageCell

class ImageCell: UICollectionViewCell{
var url: URL?{
didSet{
self.fetchImage(withURL: url!)
}
}
@IBOutlet var imageView: UIImageView!

private func fetchImage(withURL url: URL) {
DispatchQueue.global(qos: .userInitiated).async { [weak self] in
guard let data = try? Data(contentsOf: url) else {
return
}

guard let image = UIImage(data: data) else {
print("Couldn't convert data to UIImage")
print("The url is")
print(url)
return
}

// If by the time the async. fetch finishes, the imageURL is still the same, update the UI (in the main queue)
if self?.url == url {
DispatchQueue.main.async {
self?.imageView.image = image
}
}
}
}

}

GITHUB

Here is my project on github

最佳答案

要从通过拖放 Google 图片提供的 URL 中提取图片 URL,您可以将这些扩展名添加到 URL。然后,在保存 url 的变量 (url) 上,您可以使用 url!.imageURL 而不仅仅是 url! 来访问图像 url >

extension URL {
var imageURL: URL {
if let url = UIImage.urlToStoreLocallyAsJPEG(named: self.path) {
// this was created using UIImage.storeLocallyAsJPEG
return url
} else {
// check to see if there is an embedded imgurl reference
for query in query?.components(separatedBy: "&") ?? [] {
let queryComponents = query.components(separatedBy: "=")
if queryComponents.count == 2 {
if queryComponents[0] == "imgurl", let url = URL(string: queryComponents[1].removingPercentEncoding ?? "") {
return url
}
}
}
return self.baseURL ?? self
}
}
}

extension UIImage
{
private static let localImagesDirectory = "UIImage.storeLocallyAsJPEG"

static func urlToStoreLocallyAsJPEG(named: String) -> URL? {
var name = named
let pathComponents = named.components(separatedBy: "/")
if pathComponents.count > 1 {
if pathComponents[pathComponents.count-2] == localImagesDirectory {
name = pathComponents.last!
} else {
return nil
}
}
if var url = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first {
url = url.appendingPathComponent(localImagesDirectory)
do {
try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
url = url.appendingPathComponent(name)
if url.pathExtension != "jpg" {
url = url.appendingPathExtension("jpg")
}
return url
} catch let error {
print("UIImage.urlToStoreLocallyAsJPEG \(error)")
}
}
return nil
}

func storeLocallyAsJPEG(named name: String) -> URL? {
if let imageData = self.jpegData(compressionQuality: 1.0) {
if let url = UIImage.urlToStoreLocallyAsJPEG(named: name) {
do {
try imageData.write(to: url)
return url
} catch let error {
print("UIImage.storeLocallyAsJPEG \(error)")
}
}
}
return nil
}
}

关于ios - Swift:拖放,保存来自谷歌图像的图像网址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59314434/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com