My app uses data from 11 JSON files (size between 70 kb and 200 kb each). During the same user session, the user might access to data from any of the 11 files, at different times. So obviously I want to download these files only once and I want to be able to access their content anytime during the same session. When the app launches I download the files immediately, then allow the user to navigate anywhere (see code below for 1 file but it would be the same for the others) At the moment, I am storing the content of each file in a static array of Strings, so that it is accessible from any other class.
Questions: 1. is it dangerous for performance memory wise ? 2. can the array variable be emptied or destroyed or lost in any way during a user session (for example if the user presses the Home button and does activities requiring lots of memory with his phone, then go back to my app)? 3. is there a better practice for my need (singleton for example?) I want to avoid storing the files with NSUserDefaults
What I am doing at the moment (with Alamofire and SwiftyJSON)
class MyClass: UIViewController {
let username = "..."
let password = "..."
let url = "..."
static var staticArrayOfJS: [String] = []
var arrayOfJS: [String] = []
override func viewDidLoad() {
super.viewDidLoad()
fetchJS()
}
func fetchJS() { //this is intended to be executed only once
let credentialData = "\(username):\(password)".data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue))!
let base64Credentials = credentialData.base64EncodedString()
let headers = [
"Authorization": "Basic \(base64Credentials)",
"Accept": "application/json",
"Content-Type": "application/json" ]
Alamofire.request(url, method: .get, parameters: nil,encoding: URLEncoding.default, headers: headers) .responseJSON { response in
guard let data = response.data else {
print("no data returned")
return
}
do {
let json = try JSON(data: data)
let indexOfLastItem = json.array?.count
for i in 0..<indexOfLastItem! {
self.arrayOfJS.append(json[i]["message"].string!)
}
MyClass.staticArrayOfJS = self.arrayOfJS
}
catch {
print("error parsing json data")
}
}
}
static func getJSMessage(id: Int) -> String { // this is intended to be accessed from external classes, several times within the same user session
return staticArrayOfJS[id]
}
}
Example of a JSON file content
[{"id":0,"message":"my message 0"}, {"id":1,"message":"my message 1"}, ...