JSON图像解析IOS Swift 3.0

Posted

技术标签:

【中文标题】JSON图像解析IOS Swift 3.0【英文标题】:JSON Image Parsing IOS Swift 3.0 【发布时间】:2016-12-08 09:55:07 【问题描述】:

我是 ios 快速开发的新手。我正在尝试使用动态数据/url 进行 json 图像解析,我尝试在没有结果的情况下搜索在表格视图或列表视图中显示数据和图像的示例,有人可以帮助我完成这项任务吗?

下面是图片解析的链接

http://www.androidbegin.com/tutorial/jsonparsetutorial.txt

【问题讨论】:

您是否要在 cellforrow 中加载图像并在 tableview 单元格中设置?... 你能分享你的代码吗?你想解析数据?问题不是 100% 可以理解的 是的,使用 json 提要并在表格视图中显示 @Dheeraj D bro 我基本上是 android 人学习 IOS 试图在 ios 中进行 json 图像解析,需要一个很好的例子来学习 json imge 解析 尝试关注***.com/questions/16663618/… 【参考方案1】:

作为一个新手,我认为这个库可以减轻你的大部分工作,

SwiftyJSON

语法对开发人员非常友好和简单,没有if let 语法和嵌套的困扰。示例用法通过简单的一行创建 json let json = JSON(data : data) 以及更多自定义数据类型。看看这个库

let rank = json["worldpopulation"][0]["rank"].int let country = json["worldpopulation"][0]["country"].string let flag = json["worldpopulation"][0]["flag"].string

【讨论】:

【参考方案2】:
    func countriesResponseReceived(response : NSDictionary)
    
        let arrCountries = (response.object(forKey: "worldpopulation")) as! NSArray

        for dict in arrCountries!
        
            let dictData = dict as! NSDictionary
            let rank = dictData.object(forKey: "rank") as! NSInteger
            let country = dictData.object(forKey: "country") as! String
            let flag = dictData.object(forKey: "flag") as! String
        
    

【讨论】:

【参考方案3】:

斯威夫特 3.0 创建新的 Xcode 项目 采取一张表视图 创建 tableViewCell 文件 创建 NSObject 类文件 拿一张标签(国名) 取一个 imageView(flag) 把下面的代码放在正确的地方(注意:在开始代码之前提到地方)

ViewController 代码

import UIKit

class ViewController: UIViewController , UITableViewDelegate , UITableViewDataSource 

    @IBOutlet var imgTable: UITableView!
    var ArrayData:[Datad] = []
    override func viewDidLoad() 
        super.viewDidLoad()
        service()
        // Do any additional setup after loading the view, typically from a nib.
    

    override func didReceiveMemoryWarning() 
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int 
        return ArrayData.count
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
        let cell = tableView.dequeueReusableCell(withIdentifier: "CellDemo") as! ImageTableViewCell
        let objarr = ArrayData[indexPath.row]
        cell.lblContry.text = objarr.Country
     cell.imgflag.setImageFrom(imageURLString: objarr.Countryflag, completionHandler:  (complete, image, error) in
        )
        return cell

    
    func service()
    
       let url = URL(string: "http://www.androidbegin.com/tutorial/jsonparsetutorial.txt")
        var urlRequest = URLRequest(url: url!, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 60)
        urlRequest.httpMethod = "GET"
        let session = URLSession.shared
        let task = session.dataTask(with: urlRequest)  (data, response, errorresponce) in

            if errorresponce != nil
            
                print(errorresponce?.localizedDescription ?? "Value Not Found")
            
            else
            
                do
                
                    if let dictionary = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
                    
                        DispatchQueue.main.async 
                            for datacon in (dictionary.value(forKey: "worldpopulation") as! NSArray)                        

                                let cellonr = Datad(dictionary: datacon as! NSDictionary )

                                self.ArrayData.append(cellonr)
                                self.imgTable.reloadData()

                            

                        

                                           
                    else
                    
                        print("value not found")
                    

                
                catch let error as Error!
                
                    print(error.localizedDescription)
                
            
        
        task.resume()
    


TableView 单元格代码

import UIKit

class ImageTableViewCell: UITableViewCell 

    @IBOutlet var lblContry: UILabel!
    @IBOutlet var imgflag: UIImageView!
    override func awakeFromNib() 
        super.awakeFromNib()
        // Initialization code
    

    override func setSelected(_ selected: Bool, animated: Bool) 
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    


NSObject 文件

import UIKit

class Datad: NSObject 

    var Country:String!
    var Countryflag:String!
    init(dictionary:NSDictionary)
    
        Country =  (dictionary.value(forKey: "country") as! String)
        Countryflag =  (dictionary.value(forKey: "flag") as! String)

    


先复制这两个文件(注意下面2 File Name Not Change Strikly Follow)

ImageDownloadManager.swift

import Foundation
import UIKit

typealias DownloadHandler = (_ success: Bool,  _ image: UIImage?,  _ error: Error?) -> Void
typealias DownloadProgressHandler = (_ totalBytesExpected : Int64,  _ bytesDownloaded: Int64, _ error : Error?) -> Void

private var kImageURLKey : String = "imageURLKey"

extension UIImageView

    var imageURLId : String

        get
            return objc_getAssociatedObject(self, &kImageURLKey) as! String
        
        set(newValue)
            objc_setAssociatedObject(self, &kImageURLKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        
    

    func setImageFrom(imageURLString : String,
                      placeHolderImage: UIImage? = nil,
                      completionHandler: DownloadHandler?) 

        if (imageURLString.characters.count > 0)

            if ((placeHolderImage) != nil)
                self.image = placeHolderImage;
            

            self.imageURLId = imageURLString

            ImageDownloadManager.sharedManager.getImageFromURL(imageURLString: imageURLString)
             (success : Bool, image : UIImage?, error :Error?) in

                if (success)
                    self.isUserInteractionEnabled = true
                    self.updateImage(image: image!, imageUrl: imageURLString)
                

                if ((completionHandler) != nil)
                    completionHandler!(success, image, error)
                
            
        
    

    func setImageFrom(imageURLString : String,
                      placeHolderImage: UIImage? = nil,
                      progressHandler: @escaping DownloadProgressHandler,
                      completionHandler: DownloadHandler?) 

        if (imageURLString.characters.count > 0)

            if ((placeHolderImage) != nil)
                self.image = placeHolderImage;
            

            self.imageURLId = imageURLString


            ImageDownloadManager.sharedManager.getImageFromURL(imageURLString: imageURLString,
                                                               progessHandler:  (expectedBytes:Int64, downloadedBytes:Int64, error:Error?) in
                                                                if error != nil 
                                                                    completionHandler!(false, nil, error)
                                                                else
                                                                    progressHandler(expectedBytes, downloadedBytes, nil)
                                                                


            ,
                                                               completionHandler:   (success:Bool, image:UIImage?, error:Error?) in

                                                                if (success)
                                                                    self.updateImage(image: image!, imageUrl: imageURLString)
                                                                

                                                                if ((completionHandler) != nil)
                                                                    completionHandler!(success, image, error)
                                                                
            )
        

    

    private func updateImage(image:UIImage, imageUrl:String) 

        if (imageUrl == imageURLId)
        
            UIView.transition(with: self,
                              duration: 0.4,
                              options: .transitionCrossDissolve,
                              animations: 
                                self.image = image;
            ,
                              completion: nil)
        
    

UIImageView+AsyncLoad.swift

import UIKit


struct ImageDownloadInfo 
    let downloadURLString : String
    let downloadTask : URLSessionTask
    let progressHandler : DownloadProgressHandler?
    let completionHandler : DownloadHandler?


class ImageDownloadManager: NSObject 

    static let sharedManager : ImageDownloadManager = ImageDownloadManager()

    var imageLoaderQueue : [String:ImageDownloadInfo] = [:]
    var imageCache : NSCache<NSString, UIImage> = NSCache()

    lazy var downloadsSession : URLSession = URLSession(configuration: URLSessionConfiguration.default)
    lazy var downloadDelegateSession : URLSession = URLSession(configuration: URLSessionConfiguration.default, delegate: sharedManager, delegateQueue: OperationQueue.main)

    func getImageFromURL(imageURLString:String,
                         completionHandler:@escaping DownloadHandler) 

        let cachedImage : UIImage? = imageCache.object(forKey: imageURLString as NSString)

        if cachedImage != nil 
            completionHandler(true, cachedImage, nil)
        else 
            downloadImageFor(imageURLString: imageURLString, downloadHandler: completionHandler)
        
    

    func getImageFromURL(imageURLString:String,
                         progessHandler: @escaping DownloadProgressHandler,
                         completionHandler: @escaping DownloadHandler )
        let cachedImage : UIImage? = imageCache.object(forKey: imageURLString as NSString)

        if cachedImage != nil 
            progessHandler(1, 1, nil)
            completionHandler(true, cachedImage, nil)
        else 
            downloadImageFor(imageURLString: imageURLString, progressHandler: progessHandler, completionHandler:completionHandler)
        
    

    private func downloadImageFor(imageURLString:String,
                                  downloadHandler: @escaping DownloadHandler) 


        var imageDownloadInfo: ImageDownloadInfo? = imageLoaderQueue[imageURLString]

        if imageDownloadInfo == nil 

            let imageLoaderTask = downloadsSession.dataTask(with: URL(string: imageURLString)!, completionHandler:  (data : Data?, response : URLResponse?, error : Error?) in

                OperationQueue.main.addOperation(

                    if (error != nil)
                        downloadHandler(false, nil, error)
                    
                    else
                        let image = UIImage(data: data!)
                        if image != nil 
                            ImageDownloadManager.sharedManager.imageCache.setObject(image!, forKey: imageURLString as NSString)
                            downloadHandler(true, image, nil)
                        
                        else 
                            downloadHandler(false, nil, error)
                        
                    
                    ImageDownloadManager.sharedManager.imageLoaderQueue[imageURLString] = nil
                )
            )

            imageDownloadInfo = ImageDownloadInfo(downloadURLString: imageURLString,
                                                  downloadTask: imageLoaderTask,
                                                  progressHandler: nil,
                                                  completionHandler:nil)

            imageLoaderQueue[imageURLString] = imageDownloadInfo
            imageDownloadInfo?.downloadTask.resume()
        
    

    private func downloadImageFor(imageURLString:String,
                                  progressHandler: @escaping DownloadProgressHandler,
                                  completionHandler: @escaping DownloadHandler) 

        var imageDownloadInfo: ImageDownloadInfo? = imageLoaderQueue[imageURLString]

        if imageDownloadInfo == nil 

            let imageLoaderTask = downloadDelegateSession.downloadTask(with: URL(string: imageURLString)!)

            imageDownloadInfo = ImageDownloadInfo(downloadURLString: imageURLString,
                                                  downloadTask: imageLoaderTask,
                                                  progressHandler: progressHandler,
                                                  completionHandler:completionHandler)

            imageLoaderQueue[imageURLString] = imageDownloadInfo
            imageDownloadInfo?.downloadTask.resume()
        

    


extension ImageDownloadManager : URLSessionDownloadDelegate 

    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL)

        let imageUrl : String = (downloadTask.originalRequest?.url?.absoluteString)!
        let imageDownloadInfo: ImageDownloadInfo? = imageLoaderQueue[imageUrl]

        if imageDownloadInfo != nil 


            do 
                let data = try Data(contentsOf: location)

                let image = UIImage(data: data)

                ImageDownloadManager.sharedManager.imageCache.setObject(image!, forKey: imageUrl as NSString)

                if let completionHandler = imageDownloadInfo?.completionHandler 

                    completionHandler(true, image, nil)
                

             catch 
                print(error.localizedDescription)
            
        
    

    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64)

        let imageUrl = downloadTask.originalRequest?.url?.absoluteString
        let imageDownloadInfo: ImageDownloadInfo? = imageLoaderQueue[imageUrl!]

        if imageDownloadInfo != nil 

            if let progressHandler = imageDownloadInfo?.progressHandler 
                progressHandler(totalBytesExpectedToWrite, totalBytesWritten, nil)
            
        
    


【讨论】:

以上是关于JSON图像解析IOS Swift 3.0的主要内容,如果未能解决你的问题,请参考以下文章

iOS swift 3.0 本地 JSON 解析崩溃

SWIFT/iOS:将 XML 数据(RSS 提要)解析为明文,将图像和视频添加到 textview

在 iOS 错误中解析 JSON 图像 url

iOS 中 JSON 解析中的 TableView 中未显示图像

Swift 3.0 图像集

Swift 3.0 将图像写入目录