Сначала у меня есть среда:
Swift 5 Xcode 11.4.1 (11E503a)
Вот мой код
import UIKit
import CoreML
import Vision
import Alamofire
import SwiftyJSON
import SDWebImage
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
//MARK: Outlets
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var label: UILabel!
//MARK: Variables
let imagePicker = UIImagePickerController()
let wikipediaURL = "https://en.wikipedia.org/w/api.php"
override func viewDidLoad() {
super.viewDidLoad()
imagePicker.delegate = self
// false uses (UIImagePickerController.InfoKey).originalImage
// true uses (UIImagePickerController.InfoKey).editedImage, permits to crop the image
imagePicker.allowsEditing = true
imagePicker.sourceType = .camera
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
// User picked an image
if let userImage = info[.editedImage] as? UIImage {
guard let userCIImage = CIImage(image: userImage) else {
fatalError("Cannot convert image to CIImage")
}
detect(image: userCIImage)
}
imagePicker.dismiss(animated: true, completion: nil)
}
func detect(image: CIImage) {
guard let model = try? VNCoreMLModel(for: FlowerClassifier().model) else {
fatalError("Cannot import model")
}
let request = VNCoreMLRequest(model: model) { (request, error) in
guard let classification = request.results?.first as? VNClassificationObservation else {
fatalError("Could not classify image.")
}
self.navigationItem.title = classification.identifier.capitalized
self.requestInfo(flowerName: classification.identifier)
}
let handler = VNImageRequestHandler(ciImage: image)
do {
try handler.perform([request])
} catch {
print(error)
}
}
func requestInfo(flowerName: String) {
let parameters: [String:String] = [
"action": "query",
"format": "json",
"formatversion": "2",
"prop": "extracts|pageimages",
"exlimit": "1",
"titles": flowerName,
"exintro": "",
"indexpageids": "",
"redirects": "1",
"pithumbsize": "500"
]
request(wikipediaURL, method: .get, parameters: parameters).responseJSON { (response) in
if response.result.isSuccess {
print("Response Value: \(JSON(response.result.value!))")
/* To get the pageid:
query + pageids + firstElement [0]
To get extract:
query + pages + pageid + extract
*/
let flowerJSON: JSON = JSON(response.result.value!)
let pageid = flowerJSON["query"]["pageids"][0].stringValue
let flowerDescription = flowerJSON["query"]["pages"][pageid]["extract"].stringValue
let flowerImgURL = flowerJSON["query"]["pages"][pageid]["thumbnail"]["source"].stringValue
self.imageView.sd_setImage(with: URL(string: flowerImgURL))
self.label.numberOfLines = 0
self.label.text = flowerDescription
self.label.sizeToFit()
} else {
fatalError("Error in JSON response. \(String(describing: response.result.error))")
}
}
}
//MARK: IBActions
@IBAction func cameraTapped(_ sender: UIBarButtonItem) {
present(imagePicker, animated: true, completion: nil)
}
}
И когда я попытался использовать свойства flower JSON, flowerDescription, flowerImgURL Я получил нулевые значения, единственное значение, которое я получил, это pageid
Вот данные JSON, которые я получил после запроса
{
"batchcomplete" : true,
"query" : {
"normalized" : [
{
"from" : "artichoke",
"to" : "Artichoke",
"fromencoded" : false
}
],
"pages" : [
{
"pageid" : 1120742,
"title" : "Artichoke",
"pageimage" : "Artichoke_J1.jpg",
"ns" : 0,
"thumbnail" : {
"height" : 500,
"source" : "https:\/\/upload.wikimedia.org\/wikipedia\/commons\/thumb\/6\/6d\/Artichoke_J1.jpg\/368px-Artichoke_J1.jpg",
"width" : 368
},
"extract" : "<p class=\"mw-empty-elt\">\n<\/p>\n\n<p class=\"mw-empty-elt\">\n<\/p>\n<p>The <b>globe artichoke<\/b> (<i>Cynara cardunculus<\/i> var. <i>scolymus<\/i>), also known by the names <b>French artichoke<\/b> and <b>green artichoke<\/b> in the U.S., is a variety of a species of thistle cultivated as a food.\n<\/p><p>The edible portion of the plant consists of the flower buds before the flowers come into bloom. The budding artichoke flower-head is a cluster of many budding small flowers (an inflorescence), together with many bracts, on an edible base. Once the buds bloom, the structure changes to a coarse, barely edible form. Another variety of the same species is the cardoon, a perennial plant native to the Mediterranean region. Both wild forms and cultivated varieties (cultivars) exist.\n<\/p>"
}
],
"pageids" : [
"1120742"
]
},
"warnings" : {
"extracts" : {
"warnings" : "HTML may be malformed and\/or unbalanced and may omit inline images. Use at your own risk. Known problems are listed at https:\/\/www.mediawiki.org\/wiki\/Extension:TextExtracts#Caveats."
}
}
}
Как вы можете видите, что на самом деле данные есть, но как только я пытаюсь назначить данные переменным, эта информация исчезает.