웹 사이트에서 JSON 파일의 내용을 가져온 다음 해당 내용을 저장하는 방법을 알아 내려고했습니다. 실제 {...} 객체를 iOS의 파일 (XCode 포함)에 저장합니다. iOS를 처음 접했기 때문에 온라인으로 보일 것이라고 생각했지만 적용 가능한 것은 없습니다. 콘텐츠의 바이트 크기가 아닌 JSON 파일 콘텐츠 자체를 실제로 얻는 방법은 무엇입니까?
통화 설정 방법은 다음과 같습니다.
func test() {
let url = NSURL(string: "https://www.somesite.com/file.json")
let request = NSURLRequest(url: url! as URL)
let session = URLSession.shared
var json: Any
let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error -> Void in
if let data = data {
**[PROBLEM APPEARS TO BE HERE]** json = try JSONSerialization.jsonObject(with: data, options[])
let dataToSave = try JSONSerialization.data(withJSONObject: json, options:[])
print(dataToSave)
}
})
task.resume()
}
또한 NSString (data : data, encoding : String.Encoding.utf8.rawValue) 와 같은 것을 시도했지만 파일에 저장할 때 읽을 때 네이티브 JSON 디코더에서 인식하지 못하는 콘텐츠의 이스케이프 된 문자열을 생성합니다. 파일.
지금까지 몇 주 동안 iOS 와 XCode 11.5 에 빠져 들었지만 위에 지정된 질문에 대한 답을 얻은 것 같습니다. 간단히 말해, 디스크 기반 JSON 읽기 및 쓰기 동작은 비동기 웹 요청으로 동일한 작업을 시도하는 것과 크게 다르며 웹 사이트 JSON 콘텐츠를 로컬 디스크에 저장하려면 "도우미"기능을 연결해야합니다.
웹 요청을 만드는 기본 기능 :
func test1() {
var targetUrl = NSURL(string: "https://www.somesite.com/file.json")
let request = NSURLRequest(url: targetUrl! as URL)
let session = URLSession.shared
let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error -> Void in
if let data = data {
/* To avoid errors about "Invalid conversion from throwing function of type '(Data?,URLResponse?,Error?) throws -> Void' to non-throwing function type '(Data?,URLResponse?,Error?) -> Void'", when attempting to manipulate data here, pass data containing the file content to a helper function. */
self.test2Helper(contentData: data.self)
}
})
task.resume()
return
}
웹 사이트에서 JSON 콘텐츠를 저장하기위한 도우미 기능 :
func test2Helper(contentData: Data) {
/* Retrieve filepath information for app's Documents folder on device */
let appDocumentsFolder = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let fullPath = appDocumentsFolder.appendingPathComponent("website").appendingPathExtension("json")
/* For manually opening the file for verification, show the path */
print(fullPath)
/* Save the JSON content to the file */
do {
/* Build JSON Data Object */
let json = try JSONSerialization.jsonObject(with: contentData)
/* Save JSON Data to Documents */
let data = try JSONSerialization.data(withJSONObject: json, options: [])
try data.write(to: fullPath, options: [])
/* For testing, show completion */
print("JSON content from website saved to disk.")
}
catch {
print(error)
}
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다