我尝试读取zip文件中的json文件,在使用alamofire下载文件后,我使用SSZipArchive提取了文件。我从zip中获取了2个json文件,但无法读取json的内容。我如何读取该文件?
这是我的代码:
@IBAction func downloads(_ sender: UIButton){
let urlString : String = ""
let destination = DownloadRequest.suggestedDownloadDestination(for: .documentDirectory)
Alamofire.download(urlString, method: .get, encoding: URLEncoding.default, to: destination)
.downloadProgress(queue: DispatchQueue.global(qos: .utility)) { progress in
print("Progress: \(progress.fractionCompleted)")
print(progress)
}
.validate { request, response, temporaryURL, destinationURL in
return .success
}
.responseJSON { response in
print(response)
debugPrint(response)
print(response.destinationURL?.path)
print(response.destinationURL?.absoluteString)
let fileName = response.destinationURL!.path
guard let unzipDirectory = self.unzipPath(fileName: fileName) else {return}
let success = SSZipArchive.unzipFile(atPath: (response.destinationURL?.path)!, toDestination: unzipDirectory)
print(success)
print(unzipDirectory)
if !success {
return
}
var items: [String]
do {
items = try FileManager.default.contentsOfDirectory(atPath: unzipDirectory)
for item in items{
print("jsonFile: \(item)")
}
} catch {
return
}
}
}
func unzipPath(fileName:String) -> String? {
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString
let pathWithComponent = path.appendingPathComponent("\(fileName)")
do {
try FileManager.default.createDirectory(atPath: pathWithComponent, withIntermediateDirectories: true, attributes: nil)
} catch {
return nil
}
return pathWithComponent
}
此屏幕截图响应:
不确定,但对于JSON可读,您可以调用此方法
func readJson() {
let url = Bundle.main.url(forResource: "input_ios", withExtension: "json")
let data = NSData(contentsOf: url!)
do {
let object = try JSONSerialization.jsonObject(with: data! as Data, options: .allowFragments)
if let dictionary = object as? [String: AnyObject] {
if let Timeline = dictionary["timeline"] as? [[String:Any]] {
timelArr = Timeline
feedTbl.reloadData()
}
}
} catch {
}
}
并更改文件名(您的文件名),然后获取数据。我在表格视图中显示。