Need to adjust NSJSONSerialization to iOS10 - swift

After upgrading to iOS10 users started complaining about crashes of my app.
I am testing it with iOS10 on the simulator and indeed the app crashes with a message saying "Could not cast value of type '__NSArrayI' to 'NSMutableArray'". Here's my code, please help:
import Foundation
protocol getAllListsModel: class {
func listsDownloadingComplete(downloadedLists: [ContactsList])
}
class ListsDownloader: NSObject, NSURLSessionDataDelegate{
//properties
weak var delegate: getAllListsModel!
var data : NSMutableData = NSMutableData()
func downloadLists() {
let urlPath: String = "http://..."
let url: NSURL = NSURL(string: urlPath)!
var session: NSURLSession!
let configuration = NSURLSessionConfiguration.ephemeralSessionConfiguration() //defaultSessionConfiguration()
session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: nil)
let task = session.dataTaskWithURL(url)
task.resume()
}
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
self.data.appendData(data);
}
func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
if error != nil {
print("Failed to download data")
}else {
self.parseJSON()
print("Lists downloaded")
}
}
func parseJSON() {
var jsonResult: NSMutableArray = NSMutableArray()
do{
try jsonResult = NSJSONSerialization.JSONObjectWithData(self.data, options:NSJSONReadingOptions.AllowFragments) as! NSMutableArray
} catch let error as NSError {
print(error)
}
var jsonElement: NSDictionary = NSDictionary()
var downloadedLists: [ContactsList] = []
for i in 0...jsonResult.count-1 {
jsonElement = jsonResult[i] as! NSDictionary
let tempContactsList = ContactsList()
//the following insures none of the JsonElement values are nil through optional binding
let id = jsonElement["id"] as? String
let name = jsonElement["name"] as? String
let pin = jsonElement["pin"] as? String
let lastUpdated = jsonElement["created"] as? String
let listAdminDeviceID = jsonElement["admin"] as? String
tempContactsList.id = id
tempContactsList.name = name
tempContactsList.pin = pin
tempContactsList.lastUpdated = lastUpdated
tempContactsList.listAdmin = listAdminDeviceID
downloadedLists.append(tempContactsList)
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.delegate.listsDownloadingComplete(downloadedLists)
})
}
}

Even in iOS 9, there was no guarantee NSJSONSerialization.JSONObjectWithData(_:options:) would return mutable object or not. You should have specified NSJSONReadingOptions.MutableContainers.
And in your code, you are not modifying jsonResult, which means you have no need to declare it as NSMutableArray. Just replace NSMutableArray to NSArray, and then you have no need to specify NSJSONReadingOptions.MutableContainers.
But as vadian is suggesting, you better use Swift types rather than NSArray or NSDictionary. This code should work both in iOS 9 and 10.
func parseJSON() {
var jsonResult: [[String: AnyObject]] = [] //<- use Swift type
do{
try jsonResult = NSJSONSerialization.JSONObjectWithData(self.data, options: []) as! [[String: AnyObject]] //<- convert to Swift type, no need to specify options
} catch let error as NSError {
print(error)
}
var downloadedLists: [ContactsList] = []
for jsonElement in jsonResult { //<- your for-in usage can be simplified
let tempContactsList = ContactsList()
//the following insures none of the JsonElement values are nil through optional binding
let id = jsonElement["id"] as? String
let name = jsonElement["name"] as? String
let pin = jsonElement["pin"] as? String
let lastUpdated = jsonElement["created"] as? String
let listAdminDeviceID = jsonElement["admin"] as? String
tempContactsList.id = id
tempContactsList.name = name
tempContactsList.pin = pin
tempContactsList.lastUpdated = lastUpdated
tempContactsList.listAdmin = listAdminDeviceID
downloadedLists.append(tempContactsList)
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.delegate.listsDownloadingComplete(downloadedLists)
})
}
Try this and check it on iOS 10 devices.
(The as! conversion would cause some weird crashes when your server is malfunctioning, but that would be another issue, so I keep it there.)

Related

Saving JSON into Realm

For my project I want to save data I'm getting from an API in realm and then display it in a table view.
The JSON will look like this:
{"books":[{"author":"Chinua Achebe", "title":"Things Fall Apart","imageLink":"http://books.google.com/books/content?id=plk_nwEACAAJ&printsec=frontcover&img=1&zoom=5&source=gbs_api"}]}
I've tried a few different things, but I can't figure out how to decode and store the JSON properly. I have used this function before for parsing the JSON, but when I add the realm Code I'm getting errors.
My function for fetching the JSON is:
func fetchArticle(){
let urlRequest = URLRequest(url: URL(string: "https:/mocki.io/v1/89aa9fe9-fdba-463f-99b3-5d8b6bc1d32e")!)
let task = URLSession.shared.dataTask(with: urlRequest) { (data,response,error) in
if error != nil {
print(error)
return
}
self.books = [Books]()
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String: AnyObject]
if let booksFromJson = json["books"] as? [[String : AnyObject]]{
for bookFromJson in booksFromJson {
let book = Books()
if let title = bookFromJson["title"] as? String, let author = bookFromJson["author"] as? String, let imageLink = bookFromJson["imageLink"] as? String {
book.author = author
book.title = title
book.imageLink = imageLink
}
self.books?.append(book)
let realm = try! Realm()
for books in bookFromJson {
try! realm.write {
realm.add(books, update: .all)
}
}
DispatchQueue.main.async {
self.tableview.reloadData()
}
} catch let error {
print(error)
}
}
task.resume()
}
}
}
This is my Struct:
class Books: Object, Decodable {
#objc dynamic var author: String?
#objc dynamic var imageLink: String?
#objc dynamic var title: String?
convenience init(author: String, imageLink: String, title: String) {
self.init()
self.author = author
self.imageLink = imageLink
self.title = title
}
override static func primaryKey() -> String? {
return "author"
}
private enum CodingKeys: String, CodingKey {
case author
case imageLink
case title
}
}
This are the errors im getting in the func:
Invalid conversion from throwing function of type '(Data?, URLResponse?, Error?) throws -> Void' to non-throwing function type '(Data?, URLResponse?, Error?) -> Void'
'let' declarations cannot be computed properties
There are probably a 100 different ways to map your json to a realm object but let's keep it simple. First I assume your incoming json may be several books so it would look like this
let jsonStringWithKey = """
{
"books":
[{
"author":"Chinua Achebe",
"title":"Things Fall Apart",
"imageLink":"someLink"
},
{
"author":"another author",
"title":"book title",
"imageLink":"another link"
}]
}
"""
So encode it as data
guard let jsonDataWithKey = jsonStringWithKey.data(using: .utf8) else { return }
Then, using JSONSerialization, map it to an array. Keeping in mind the top level object is "books" and AnyObject will be all of the child data
do {
if let json = try JSONSerialization.jsonObject(with: jsonDataWithKey) as? [String: AnyObject] {
if let bookArray = json["books"] as? [[String:AnyObject]] {
for eachBook in bookArray {
let book = Book(withBookDict: eachBook)
try! realm.write {
realm.add(book)
}
}
}
}
} catch {
print("Error deserializing JSON: \(error)")
}
and the Realm object is
class Book: Object, Codable {
#objc dynamic var author = ""
#objc dynamic var title = ""
#objc dynamic var imageLink = ""
convenience init(withBookDict: [String: Any]) {
self.init()
self.author = withBookDict["author"] as? String ?? "No Author"
self.title = withBookDict["title"] as? String ?? "No Title"
self.imageLink = withBookDict["imageLink"] as? String ?? "No link"
}
}
Again, there are a LOT of different ways of handling this so this is kind of the basics that can be expanded on.
As a suggestion, Realm Results are live-updating objects that also have corresponding events. So a neat thing you can do is to make a results object your tableView datasource and add an observer to it.
Results objects work very much like an array.
As books are added, updated or deleted from realm, the results object will reflect those changes and an event will be fired for each one - that makes keeping your tableView updated very simple.
So in your viewController
class ViewController: NSViewController {
var bookResults: Results<PersonClass>? = nil
#IBOutlet weak var bookTableView: NSTableView!
var bookToken: NotificationToken?
self.bookResults = realm.objects(Book.self)
and then
override func viewDidLoad() {
super.viewDidLoad()
self.bookToken = self.bookResults!.observe { changes in
//update the tableView when bookResults change
You have an error in terms of where you've placed your catch statement -- it should be in line with the do { } block. This might be easier to see if you format/indent your code (Ctrl-i in Xcode).
func fetchArticle(){
let urlRequest = URLRequest(url: URL(string: "https:/mocki.io/v1/89aa9fe9-fdba-463f-99b3-5d8b6bc1d32e")!)
let task = URLSession.shared.dataTask(with: urlRequest) { (data,response,error) in
if let error = error {
print(error)
return
}
self.books = [Books]()
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String: AnyObject]
if let booksFromJson = json["books"] as? [[String : AnyObject]]{
for bookFromJson in booksFromJson {
let book = Books()
if let title = bookFromJson["title"] as? String, let author = bookFromJson["author"] as? String, let imageLink = bookFromJson["imageLink"] as? String {
book.author = author
book.title = title
book.imageLink = imageLink
}
self.books?.append(book)
let realm = try! Realm()
for books in bookFromJson {
try! realm.write {
realm.add(books, update: .all)
}
}
DispatchQueue.main.async {
self.tableview.reloadData()
}
}
}
} catch { //<-- no need for `let error`
print(error)
}
}
task.resume() //<-- Moved outside the declaration
}

'WeatherManagerDelegate' cannot be constructed because it has no accessible initializers I'm getting this error, when I'm trying to run my code

I'm getting this error on line var delegate = WeatherManagerDelegate()
import Foundation
protocol WeatherManagerDelegate {
func didUpdateWeather(weather:WeatherModel)
}
struct WeatherManager {
let weatherURL = "https://api.openweathermap.org/data/2.5/weather?&appid=d73ab8784f3b294976fc6189b3e6eba2&units=metric"
var delegate = WeatherManagerDelegate()
func fetchWeather(cityName: String) {
let urlString = "\(weatherURL)&q=\(cityName)"
performRequest(urlString: urlString)
}
func performRequest(urlString: String)
{
//Create URL
if let url = URL(string: urlString){
//Create a URL Session.
let session = URLSession(configuration: .default)
//Give session a task
let task = session.dataTask(with: url) { (data, response, error) in
if error != nil{ //on selecting url 2nd option the seletors you get select from data onwards to error and press enter and it will be set to closure format.
print(error!)
return
}
if let safeData = data {
/* let dataString = String(data: safeData, encoding: .utf8)
print(dataString!)*/
if let weather = parseJSON(weatherData: safeData) {
self.delegate.didUpdateWeather(weather:weather)
}
}
}
//Start task
task.resume()
}
}
func parseJSON(weatherData: Data) ->WeatherModel? {
let decoder = JSONDecoder()
do{
let decodeData = try decoder.decode(WeatherData.self, from: weatherData)
let name = decodeData.name
let temp = decodeData.main.temp
print(decodeData.main.temp_max)
print(decodeData.main.temp_min)
print(decodeData.sys.country)
print(decodeData.weather[0].description)
let id = decodeData.weather[0].id
let weather = WeatherModel(conditionId: id, cityName: name, temperature: temp)
print(weather.conditionName)
print(weather.temperatureString)
}
catch{
print(error)
return nil
}
}
}
and when I'm trying to make it an optional
var delegate = WeatherManagerDelegate?()
I'm getting this error
No exact matches in call to initializer
Replace
var delegate = WeatherManagerDelegate()
with
weak var delegate: WeatherManagerDelegate?
and update the calls to read self.delegate?.didUpdateWeather()
WeatherManager should not be responsible for creating its own delegate, that is something that should come from wherever it is begin used.
The weak attribute is almost always necessary when using delegates to avoid retain cycles.
Since weak can only be applied to class objects, you also need to indicate that in the protocol definition:
protocol WeatherManagerDelegate: AnyObject { ... }

Swift NSJSONSerialization.JSONObjectWithData doesn't handle empty Data

I have a data downloader class that downloads data from mySQL server.
The problem I am having is when the result is null - the app crashes with error message
Could not cast value of type '__NSArray0' (0x105548918) to 'NSMutableArray' (0x105549c00).
class userDetailsDownloader: NSObject, NSURLSessionDataDelegate {
weak var delegate: getUserDetails!
var data : NSMutableData = NSMutableData()
func downloadUserDetails(userEmail: String) {
let urlPath: String = "http://intouchmobile.co/phpscripts/getuserpassword.php?email=\(userEmail)"
let url: NSURL = NSURL(string: urlPath)!
var session: NSURLSession!
let configuration = NSURLSessionConfiguration.ephemeralSessionConfiguration() //defaultSessionConfiguration()
session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: nil)
let task = session.dataTaskWithURL(url)
task.resume()
}
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
self.data.appendData(data);
}
func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
if error != nil
{
print("Failed to get password")
}
else
{
self.parseJSON()
print("Password Received")
}
}
func parseJSON() {
var jsonResult: NSMutableArray = NSMutableArray()
var password: String!
var firstName: String!
var lastName: String!
do{
jsonResult = try NSJSONSerialization.JSONObjectWithData(self.data, options:NSJSONReadingOptions.AllowFragments) as! NSMutableArray
} catch let error as NSError {
print(error)
}
}
Don't say as! NSMutableArray. The term as! means "crash me", so you can hardly be surprised when you do crash. Say as? NSMutableArray. Test the result for nil. If it is nil, stop.
if let jsonResult = try NSJSONSerialization.JSONObjectWithData(self.data, options:NSJSONReadingOptions.AllowFragments) as? NSMutableArray {
self.jsonResult = jsonResult
}
You may still have problems because this is never going to be a mutable array; it's just an array. So you might have to change it to:
if let jsonResult = try NSJSONSerialization.JSONObjectWithData(self.data, options:NSJSONReadingOptions.AllowFragments) as? NSArray {
self.jsonResult = NSMutableArray(array: jsonResult)
}
(But, as vadian has said in a comment, it would be even better if you could abandon use of NSArray and NSMutableArray and use Swift types instead.)
Try it like this.
if NSJSONSerialization.isValidJSONObject(data) {
//your do catch
}
That should solve your problem.

Unexpectedly found nil when unwrapping optional value - NSMutableArray - Swift

I am retrieving posts in a data handler from a DB for a news feed and I run a php script and echo the JSON encoded data back to my application, at which point the data is parsed and stored in a model of a "post", there is a protocol that is used in the view controller to get the data once it has been downloaded. My problem is that I am getting the notorious "Unexpectedly found nil when unwrapping optional value" error when I pass the NSMutableArray of "post" objects to the function "itemsDownloaded" which is function of the protocol. I checked all the values being parsed and they exist, and I also checked the count of the array to make sure it has values. The exception is occurring on the line self.delegate.itemsDownloaded(posts)
The code to handle the data is this :
import Foundation
protocol PostDataHandlerProtocol: class {
func itemsDownloaded(items: NSArray)
}
class PostDataHandler: NSObject, NSURLSessionDataDelegate {
weak var delegate: PostDataHandlerProtocol!
var data : NSMutableData = NSMutableData()
//The path to the php script to be executed
let urlPath: String = "www.something.com/myphpscript.php"
func downloadItems() {
let url: NSURL = NSURL(string: urlPath)!
var session: NSURLSession!
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: nil)
let task = session.dataTaskWithURL(url)
task.resume()
}
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
self.data.appendData(data);
}
func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
if error != nil {
print("Failed to download data")
}else {
print("Data downloaded")
self.parseJSON()
}
}
func parseJSON() {
var jsonResult: NSMutableArray = NSMutableArray()
do{
jsonResult = try NSJSONSerialization.JSONObjectWithData(self.data, options:NSJSONReadingOptions.AllowFragments) as! NSMutableArray
} catch let error as NSError {
print(error)
}
var jsonElement: NSDictionary = NSDictionary()
let posts: NSMutableArray = NSMutableArray()
for(var i = 0; i < jsonResult.count; i++)
{
jsonElement = jsonResult[i] as! NSDictionary
let post = PostModel()
//The following insures none of the JsonElement values are nil through optional binding
let username = jsonElement["username"] as? String
let imagePath = jsonElement["user_imagePath"] as? String
let postID = (jsonElement["post_id"] as! NSString).integerValue
let postRep = (jsonElement["post_rep"] as! NSString).integerValue
let postType = jsonElement["post_type"] as? String
let postDate = jsonElement["post_date"] as? String
let comment = jsonElement["comment"] as? String
post.username = username
post.imagePath = imagePath
post.postID = postID
post.postRep = postRep
post.postType = postType
post.postDate = postDate
post.comment = comment
posts.addObject(post)
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.delegate.itemsDownloaded(posts)
})
}
}
In my view controller, I create a new data handler let postHandler = PostDataHandler() and then once the view has loaded I call postHandler.downloadItems() and in the view controller declaration I conformed to the protocol and implemented itemsDownloaded:
func itemsDownloaded(items: NSArray) {
allPosts = items as! [PostModel]
indicator.stopAnimating()
self.tableVIew.reloadData()
}
Does anyone know why this is happening? I tried to look at the numerous postings regarding this error as I'm aware it's quite common, but couldn't find anything that helped me. Many of the postings say there should be a check to ensure it's not nil, the problem is I didn't think NSMutableArray can be optional, and also I checked all the values and they don't appear to be nil, so those answers did not help me. In the thread exceptions it says something related to a closure, which I think could be causing the issue, I'm just not exactly sure what or how.
None of the code that you showed ever set your PostDataHandler's delegate property to anything, so it is reasonable to suppose that it is still nil, which perfectly explains why you crash at runtime when you try to access it as if it were an actual object.

Creating and assigning a new NSManagedObject to a new NSManagedObject *sometimes* fails

I am creating a new NSManagedObject called "translation". Within the translation I need to create two additional NSManagedObjects called "phrase". Sometimes one of the phrase assignments will throw an error, but when I inspect the values they all look like they were created just fine. What gives???
Creating A Translation Object:
func getOrCreateTranslation(package: Package?, data: NSDictionary) -> Translation {
let translationId = data["id"] as! NSNumber
if let translation = self.getTranslation(translationId) {
return translation
} else {
let context = LocalDataStorage().context
let translation = NSEntityDescription.insertNewObjectForEntityForName("Translation", inManagedObjectContext: context) as! Translation
translation.id = translationId
let fromPhrase = data["from_phrase"]! as! NSDictionary
let toPhrase = data["to_phrase"]! as! NSDictionary
let pm = PhraseManager()
//*******
// *SOMETIMES* ONE OF THESE LINES FAIL WITH BAD_EXC_ACCESS code=1
translation.fromPhrase = pm.getOrCreatePhrase(fromPhrase)
translation.toPhrase = pm.getOrCreatePhrase(toPhrase)
//******
if package != nil {
package!.addTranslationObject(translation)
}
return translation
}
}
Creating A Phrase Object:
func getOrCreatePhrase(data: NSDictionary) -> Phrase {
// check if phrase exists
let phraseId = data["id"] as! NSNumber
if let phrase = self.getPhrase(phraseId) {
return phrase
} else {
let context = localDataStorage.context
let lm = LanguageManager()
let phrase = NSEntityDescription.insertNewObjectForEntityForName("Phrase", inManagedObjectContext: context) as! Phrase
phrase.id = phraseId
phrase.text = data["text"] as! String
phrase.audioUrl = data["audio_url"] as? String
let code = data["language"]!["language_code"] as! String
phrase.language = lm.getLanguageFromCode(code)
return phrase
}
}
Call Made to API:
func getPackageTranslations(package: Package, completion: ([Translation])-> Void) {
let currentLanguage: Language = LanguageManager().getCurrentLanguage()!
let urlString = baseAPIString + "/groups/\(package.id!)/translations/?language_code=\(currentLanguage.code)"
let session = NSURLSession.sharedSession()
let serachUrl = NSURL(string: urlString)
let task = session.dataTaskWithURL(serachUrl!) {
(data, response, error) -> Void in
if error != nil {
print(error?.localizedDescription)
} else {
let jsonData: NSDictionary!
do {
jsonData = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as! NSDictionary
} catch _ {
jsonData = NSDictionary()
}
let groupTranslationsData = jsonData["group_translations"] as! [NSDictionary]
var translations = [Translation]()
let context = LocalDataStorage().context
for groupTranslation in groupTranslationsData {
let translationData = groupTranslation["translation"] as! NSDictionary
let translation = TranslationManager().getOrCreateTranslation(package, data: translationData)
if translation.packages?.containsObject(package) == false {
//package.addTranslationObject(translation!)
//translation!.addPackageObject(package)
}
translations.append(translation)
}
do {
try context.save()
} catch {
print("There was a problem saving translation ")
}
dispatch_async(dispatch_get_main_queue(), {
completion(translations)
})
}
}
task.resume()
}
CoreData Context Class:
class LocalDataStorage {
let appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context: NSManagedObjectContext!
init() {
context = appDelegate.managedObjectContext
}
}
This issue occurs when you create a NSManagedObjectContext with a concurrency pattern that it should be interacted on and you perform actions on the it on a thread different from the concurrency pattern specified during its initialization.
The completion block of NSURLSession.dataTaskWithURL is run on another thread, so you must dispatch to the type of thread specified in the context creation to perform any operation successfully on it.
If the concurrency type of your context is MainQueueConcurrencyType which is used in most cases, you must perform the context save method on the main queue.
dispatch_async(dispatch_get_main_queue()) {
do {
try context.save()
} catch {
print("There was a problem saving translation ")
}
completion(translations)
}