Swift Custom Response Serializer Is Returning Images at Random

Swift Custom Response Serializer is returning images at random

Somehow the images get appended at a random order, why?

Because order is not guaranteed for asynchronous requests or blocks dispatched asynchronously.

Instead of appending images into an array, you should key them into a dictionary according to their corresponding page (e.g. pages[i] = image) (by the way, it's easier and more conventional to use for i in 0..<pages.count { ... }).

Or even better, only request the images on demand using AFNetworking's UIImageView category.

Changing response serializer for a particular call inside AFHTTPSessionManager

Try AFCompoundResponseSerializer, you may add different serializers in it.

Using a JSON array from a URL and returning rows that match a value in Swift 3

json is an array of dictionary with a key of "episode".

Don't use NSArray in Swift.

Update your code as follows:

guard let data_list = json as? [[String:Any]] else {
return
}

if let foo = data_list.first(where: {$0["episode"] as? String == "Example 1A"}) {
// do something with foo
print(foo)
} else {
// item could not be found
}

Note the two changes: the cast and the way to access the "episode". Also note the use of == for equality.

How to use NSJSONSerialization

Your root json object is not a dictionary but an array:

[{"id": "1", "name":"Aaa"}, {"id": "2", "name":"Bbb"}]

This might give you a clear picture of how to handle it:

NSError *e = nil;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &e];

if (!jsonArray) {
NSLog(@"Error parsing JSON: %@", e);
} else {
for(NSDictionary *item in jsonArray) {
NSLog(@"Item: %@", item);
}
}


Related Topics



Leave a reply



Submit