insert an ObjectId in another user - Parse and Swift - arrays

I am currently trying to save an objectId in another user's array. unfortunately, I am getting an error. here is what I tried :
let name = (PFUser.currentUser()!["FirstName"] as! String) + " " + (PFUser.currentUser()!["LastName"] as! String)
let News = News(title: "\(name) accepted your ...", user: PFUser.currentUser()!)
News.saveInBackgroundWithBlock({ (success: Bool, error: NSError?) -> Void in
if (success){
let user = self.interest.user as! User
user.joinNews(News.objectId!)
} else {
print("--------")
}
})
And here is the func joinNews I created for this :
public func joinNews(newsId: String) {
newsIds.insert(newsId, atIndex: 0)
saveInBackgroundWithBlock { (success, error) -> Void in
if error != nil {
print("\(error!.localizedDescription)")
}
}
}
Thanks in advance for you help !

The User object has a special security : it can only be updated by the user itself, that's why you get the error "User cannot be saved unless they have been authenticated via logIn or signUp"
If you want an action of the current user to modify another user object, you need to use a cloud code function, and use the Parse master key, to override this security.
This would look like :
Parse.Cloud.define("addNewsToUser", function(request, response) {
Parse.Cloud.useMasterKey();
var user = new Parse.User();
user.id = request.params.userId;
user.fetch().then(function(object) {
// modify the user here
return user.save();
}).then(function() {
response.success(user);
}, function(error) {
response.error(error.message);
});
});

Related

How to save the contents of an array that's in an Alamofire response block? [duplicate]

I have created a utility class in my Swift project that handles all the REST requests and responses. I have built a simple REST API so I can test my code. I have created a class method that needs to return an NSArray but because the API call is async I need to return from the method inside the async call. The problem is the async returns void.
If I were doing this in Node I would use JS promises but I can't figure out a solution that works in Swift.
import Foundation
class Bookshop {
class func getGenres() -> NSArray {
println("Hello inside getGenres")
let urlPath = "http://creative.coventry.ac.uk/~bookshop/v1.1/index.php/genre/list"
println(urlPath)
let url: NSURL = NSURL(string: urlPath)
let session = NSURLSession.sharedSession()
var resultsArray:NSArray!
let task = session.dataTaskWithURL(url, completionHandler: {data, response, error -> Void in
println("Task completed")
if(error) {
println(error.localizedDescription)
}
var err: NSError?
var options:NSJSONReadingOptions = NSJSONReadingOptions.MutableContainers
var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: options, error: &err) as NSDictionary
if(err != nil) {
println("JSON Error \(err!.localizedDescription)")
}
//NSLog("jsonResults %#", jsonResult)
let results: NSArray = jsonResult["genres"] as NSArray
NSLog("jsonResults %#", results)
resultsArray = results
return resultsArray // error [anyObject] is not a subType of 'Void'
})
task.resume()
//return "Hello World!"
// I want to return the NSArray...
}
}
You can pass callback, and call callback inside async call
something like:
class func getGenres(completionHandler: (genres: NSArray) -> ()) {
...
let task = session.dataTaskWithURL(url) {
data, response, error in
...
resultsArray = results
completionHandler(genres: resultsArray)
}
...
task.resume()
}
and then call this method:
override func viewDidLoad() {
Bookshop.getGenres {
genres in
println("View Controller: \(genres)")
}
}
Introduced in Swift 5.5 (iOS 15, macOS 12), we would now use the async-await pattern:
func fetchGenres() async throws -> [Genre] {
…
let (data, _) = try await URLSession.shared.dataTask(for: request)
return try JSONDecoder().decode([Genre].self, from: data)
}
And we would call it like:
let genres = try await fetchGenres()
The async-await syntax is far more concise and natural than the traditional completion handler pattern outlined in my original answer, below.
For more information, see Meet async/await in Swift.
The historic pattern is to use completion handlers closure.
For example, we would often use Result:
func fetchGenres(completion: #escaping (Result<[Genre], Error>) -> Void) {
...
URLSession.shared.dataTask(with: request) { data, _, error in
if let error = error {
DispatchQueue.main.async {
completion(.failure(error))
}
return
}
// parse response here
let results = ...
DispatchQueue.main.async {
completion(.success(results))
}
}.resume()
}
And you’d call it like so:
fetchGenres { results in
switch results {
case .failure(let error):
print(error.localizedDescription)
case .success(let genres):
// use `genres` here, e.g. update model and UI
}
}
// but don’t try to use `genres` here, as the above runs asynchronously
Note, above I’m dispatching the completion handler back to the main queue to simplify model and UI updates. Some developers take exception to this practice and either use whatever queue URLSession used or use their own queue (requiring the caller to manually synchronize the results themselves).
But that’s not material here. The key issue is the use of completion handler to specify the block of code to be run when the asynchronous request is done.
Note, above I retired the use of NSArray (we don’t use those bridged Objective-C types any more). I assume that we had a Genre type and we presumably used JSONDecoder, rather than JSONSerialization, to decode it. But this question didn’t have enough information about the underlying JSON to get into the details here, so I omitted that to avoid clouding the core issue, the use of closures as completion handlers.
Swiftz already offers Future, which is the basic building block of a Promise. A Future is a Promise that cannot fail (all terms here are based on the Scala interpretation, where a Promise is a Monad).
https://github.com/maxpow4h/swiftz/blob/master/swiftz/Future.swift
Hopefully will expand to a full Scala-style Promise eventually (I may write it myself at some point; I'm sure other PRs would be welcome; it's not that difficult with Future already in place).
In your particular case, I would probably create a Result<[Book]> (based on Alexandros Salazar's version of Result). Then your method signature would be:
class func fetchGenres() -> Future<Result<[Book]>> {
Notes
I do not recommend prefixing functions with get in Swift. It will break certain kinds of interoperability with ObjC.
I recommend parsing all the way down to a Book object before returning your results as a Future. There are several ways this system can fail, and it's much more convenient if you check for all of those things before wrapping them up into a Future. Getting to [Book] is much better for the rest of your Swift code than handing around an NSArray.
Swift 4.0
For async Request-Response you can use completion handler. See below I have modified the solution with completion handle paradigm.
func getGenres(_ completion: #escaping (NSArray) -> ()) {
let urlPath = "http://creative.coventry.ac.uk/~bookshop/v1.1/index.php/genre/list"
print(urlPath)
guard let url = URL(string: urlPath) else { return }
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let data = data else { return }
do {
if let jsonResult = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary {
let results = jsonResult["genres"] as! NSArray
print(results)
completion(results)
}
} catch {
//Catch Error here...
}
}
task.resume()
}
You can call this function as below:
getGenres { (array) in
// Do operation with array
}
Swift 3 version of #Alexey Globchastyy's answer:
class func getGenres(completionHandler: #escaping (genres: NSArray) -> ()) {
...
let task = session.dataTask(with:url) {
data, response, error in
...
resultsArray = results
completionHandler(genres: resultsArray)
}
...
task.resume()
}
Swift 5.5, async/wait-based solution
The original test URL provided by the original poster is no longer functional, so I had to change things a bit. This solution is based on a jokes API I found. That API returns a single joke, but I return it as an array of String ([String]), to keep it as consistent as possible with the original post.
class Bookshop {
class func getGenres() async -> [String] {
print("Hello inside getGenres")
let urlPath = "https://geek-jokes.sameerkumar.website/api?format=json"
print(urlPath)
let url = URL(string: urlPath)!
let session = URLSession.shared
typealias Continuation = CheckedContinuation<[String], Never>
let genres = await withCheckedContinuation { (continuation: Continuation) in
let task = session.dataTask(with: url) { data, response, error in
print("Task completed")
var result: [String] = []
defer {
continuation.resume(returning: result)
}
if let error = error {
print(error.localizedDescription)
return
}
guard let data = data else {
return
}
do {
let jsonResult = try JSONSerialization.jsonObject(with: data, options: [.mutableContainers])
print("jsonResult is \(jsonResult)")
if let joke = (jsonResult as? [String: String])?["joke"] {
result = [joke]
}
} catch {
print("JSON Error \(error.localizedDescription)")
print("data was \(String(describing: String(data: data, encoding: .utf8)))")
return
}
}
task.resume()
}
return genres
}
}
async {
let final = await Bookshop.getGenres()
print("Final is \(final)")
}
The withCheckedContinuation is how you made the Swift async function actually run in a separate task/thread.
I hope you're not still stuck on this, but the short answer is that you can't do this in Swift.
An alternative approach would be to return a callback that will provide the data you need as soon as it is ready.
There are 3 ways of creating call back functions namely:
1. Completion handler
2. Notification
3. Delegates
Completion Handler
Inside set of block is executed and returned when source is available, Handler will wait until response comes so that UI can be updated after.
Notification
Bunch of information is triggered over all the app, Listner can retrieve n make use of that info. Async way of getting info through out the project.
Delegates
Set of methods will get triggered when delegate is been called, Source must be provided via methods itself
Swift 5.5:
TL;DR: Swift 5.5 is not yet released(at the time of writing). To use swift 5.5, download swift toolchain development snapshot from here and add compiler flag -Xfrontend -enable-experimental-concurrency. Read more here
This can be achieved easily with async/await feature.
To do so, you should mark your function as async then do the operation inside withUnsafeThrowingContinuation block like following.
class Bookshop {
class func getGenres() async throws -> NSArray {
print("Hello inside getGenres")
let urlPath = "http://creative.coventry.ac.uk/~bookshop/v1.1/index.php/genre/list"
print(urlPath)
let url = URL(string: urlPath)!
let session = URLSession.shared
return try await withUnsafeThrowingContinuation { continuation in
let task = session.dataTask(with: url, completionHandler: {data, response, error -> Void in
print("Task completed")
if(error != nil) {
print(error!.localizedDescription)
continuation.resume(throwing: error!)
return
}
do {
let jsonResult = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? [String: Any]
let results: NSArray = jsonResult!["genres"] as! NSArray
continuation.resume(returning: results)
} catch {
continuation.resume(throwing: error)
}
})
task.resume()
}
}
}
And you can call this function like
#asyncHandler
func check() {
do {
let genres = try await Bookshop.getGenres()
print("Result: \(genres)")
} catch {
print("Error: \(error)")
}
}
Keep in mind that, when calling Bookshop.getGenres method, the caller method should be either async or marked as #asyncHandler
self.urlSession.dataTask(with: request, completionHandler: { (data, response, error) in
self.endNetworkActivity()
var responseError: Error? = error
// handle http response status
if let httpResponse = response as? HTTPURLResponse {
if httpResponse.statusCode > 299 , httpResponse.statusCode != 422 {
responseError = NSError.errorForHTTPStatus(httpResponse.statusCode)
}
}
var apiResponse: Response
if let _ = responseError {
apiResponse = Response(request, response as? HTTPURLResponse, responseError!)
self.logError(apiResponse.error!, request: request)
// Handle if access token is invalid
if let nsError: NSError = responseError as NSError? , nsError.code == 401 {
DispatchQueue.main.async {
apiResponse = Response(request, response as? HTTPURLResponse, data!)
let message = apiResponse.message()
// Unautorized access
// User logout
return
}
}
else if let nsError: NSError = responseError as NSError? , nsError.code == 503 {
DispatchQueue.main.async {
apiResponse = Response(request, response as? HTTPURLResponse, data!)
let message = apiResponse.message()
// Down time
// Server is currently down due to some maintenance
return
}
}
} else {
apiResponse = Response(request, response as? HTTPURLResponse, data!)
self.logResponse(data!, forRequest: request)
}
self.removeRequestedURL(request.url!)
DispatchQueue.main.async(execute: { () -> Void in
completionHandler(apiResponse)
})
}).resume()
There are mainly 3 ways of achieving callback in swift
Closures/Completion handler
Delegates
Notifications
Observers can also be used to get notified once the async task has been completed.
There are some very generic requirements that would like every good API Manager to satisfy:
will implement a protocol-oriented API Client.
APIClient Initial Interface
protocol APIClient {
func send(_ request: APIRequest,
completion: #escaping (APIResponse?, Error?) -> Void)
}
protocol APIRequest: Encodable {
var resourceName: String { get }
}
protocol APIResponse: Decodable {
}
Now Please check complete api structure
// ******* This is API Call Class *****
public typealias ResultCallback<Value> = (Result<Value, Error>) -> Void
/// Implementation of a generic-based API client
public class APIClient {
private let baseEndpointUrl = URL(string: "irl")!
private let session = URLSession(configuration: .default)
public init() {
}
/// Sends a request to servers, calling the completion method when finished
public func send<T: APIRequest>(_ request: T, completion: #escaping ResultCallback<DataContainer<T.Response>>) {
let endpoint = self.endpoint(for: request)
let task = session.dataTask(with: URLRequest(url: endpoint)) { data, response, error in
if let data = data {
do {
// Decode the top level response, and look up the decoded response to see
// if it's a success or a failure
let apiResponse = try JSONDecoder().decode(APIResponse<T.Response>.self, from: data)
if let dataContainer = apiResponse.data {
completion(.success(dataContainer))
} else if let message = apiResponse.message {
completion(.failure(APIError.server(message: message)))
} else {
completion(.failure(APIError.decoding))
}
} catch {
completion(.failure(error))
}
} else if let error = error {
completion(.failure(error))
}
}
task.resume()
}
/// Encodes a URL based on the given request
/// Everything needed for a public request to api servers is encoded directly in this URL
private func endpoint<T: APIRequest>(for request: T) -> URL {
guard let baseUrl = URL(string: request.resourceName, relativeTo: baseEndpointUrl) else {
fatalError("Bad resourceName: \(request.resourceName)")
}
var components = URLComponents(url: baseUrl, resolvingAgainstBaseURL: true)!
// Common query items needed for all api requests
let timestamp = "\(Date().timeIntervalSince1970)"
let hash = "\(timestamp)"
let commonQueryItems = [
URLQueryItem(name: "ts", value: timestamp),
URLQueryItem(name: "hash", value: hash),
URLQueryItem(name: "apikey", value: "")
]
// Custom query items needed for this specific request
let customQueryItems: [URLQueryItem]
do {
customQueryItems = try URLQueryItemEncoder.encode(request)
} catch {
fatalError("Wrong parameters: \(error)")
}
components.queryItems = commonQueryItems + customQueryItems
// Construct the final URL with all the previous data
return components.url!
}
}
// ****** API Request Encodable Protocol *****
public protocol APIRequest: Encodable {
/// Response (will be wrapped with a DataContainer)
associatedtype Response: Decodable
/// Endpoint for this request (the last part of the URL)
var resourceName: String { get }
}
// ****** This Results type Data Container Struct ******
public struct DataContainer<Results: Decodable>: Decodable {
public let offset: Int
public let limit: Int
public let total: Int
public let count: Int
public let results: Results
}
// ***** API Errro Enum ****
public enum APIError: Error {
case encoding
case decoding
case server(message: String)
}
// ****** API Response Struct ******
public struct APIResponse<Response: Decodable>: Decodable {
/// Whether it was ok or not
public let status: String?
/// Message that usually gives more information about some error
public let message: String?
/// Requested data
public let data: DataContainer<Response>?
}
// ***** URL Query Encoder OR JSON Encoder *****
enum URLQueryItemEncoder {
static func encode<T: Encodable>(_ encodable: T) throws -> [URLQueryItem] {
let parametersData = try JSONEncoder().encode(encodable)
let parameters = try JSONDecoder().decode([String: HTTPParam].self, from: parametersData)
return parameters.map { URLQueryItem(name: $0, value: $1.description) }
}
}
// ****** HTTP Pamater Conversion Enum *****
enum HTTPParam: CustomStringConvertible, Decodable {
case string(String)
case bool(Bool)
case int(Int)
case double(Double)
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let string = try? container.decode(String.self) {
self = .string(string)
} else if let bool = try? container.decode(Bool.self) {
self = .bool(bool)
} else if let int = try? container.decode(Int.self) {
self = .int(int)
} else if let double = try? container.decode(Double.self) {
self = .double(double)
} else {
throw APIError.decoding
}
}
var description: String {
switch self {
case .string(let string):
return string
case .bool(let bool):
return String(describing: bool)
case .int(let int):
return String(describing: int)
case .double(let double):
return String(describing: double)
}
}
}
/// **** This is your API Request Endpoint Method in Struct *****
public struct GetCharacters: APIRequest {
public typealias Response = [MyCharacter]
public var resourceName: String {
return "characters"
}
// Parameters
public let name: String?
public let nameStartsWith: String?
public let limit: Int?
public let offset: Int?
// Note that nil parameters will not be used
public init(name: String? = nil,
nameStartsWith: String? = nil,
limit: Int? = nil,
offset: Int? = nil) {
self.name = name
self.nameStartsWith = nameStartsWith
self.limit = limit
self.offset = offset
}
}
// *** This is Model for Above Api endpoint method ****
public struct MyCharacter: Decodable {
public let id: Int
public let name: String?
public let description: String?
}
// ***** These below line you used to call any api call in your controller or view model ****
func viewDidLoad() {
let apiClient = APIClient()
// A simple request with no parameters
apiClient.send(GetCharacters()) { response in
response.map { dataContainer in
print(dataContainer.results)
}
}
}
This is a small use case that might be helpful:-
func testUrlSession(urlStr:String, completionHandler: #escaping ((String) -> Void)) {
let url = URL(string: urlStr)!
let task = URLSession.shared.dataTask(with: url){(data, response, error) in
guard let data = data else { return }
if let strContent = String(data: data, encoding: .utf8) {
completionHandler(strContent)
}
}
task.resume()
}
While calling the function:-
testUrlSession(urlStr: "YOUR-URL") { (value) in
print("Your string value ::- \(value)")
}

Swift: Unable to append struct instance to array

I have been having some trouble creating a temporary array of user data from Firestore. Basically I created a function that retrieves user data from a Firestore collection and then iterates through each document within that collection, creating an instance of my "Thought" struct for each one. I then append each "Thought" instance to a temporary array called "tempThoughts", and the function then returns that array. The problem is that nothing seems to be appended to the array in the function. When I test it by printing out the contents of the array upon completion, it just prints an empty array.
The data itself is being read from the Firestore collection as it prints out each document the function iterates through, so I don't think that is the problem. I also tried checking to see if I am actually creating instances of the "Thought" struct properly by printing that out, and that seemed to be working. Does anyone have any idea what's wrong with the way I am appending the struct instances to the array? Perhaps there is a better way to go about doing this? Thanks for any help in advance.
Here is my current function:
func getUserDocuments() -> [Thought]{
var tempThoughts = [Thought]()
db.collection(cUser!.uid).getDocuments() { (querySnapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
} else {
for document in querySnapshot!.documents {
print("\(document.documentID) => \(document.data())")
let tempThought: Thought = Thought(id: document.get("id") as! String, content: document.get("content") as! String, dateCreated: document.get("timestamp") as! String, isFavorite: (document.get("isFavorite") != nil))
tempThoughts.append(tempThought)
}
}
}
print("TEST")
print(tempThoughts)
return tempThoughts
}
Your getDocuments is an asynchronous operation. And you've updated your tempThoughts in it's completion only. But the place where you've printed it out will get executed before the getDocuments completion. Check out the order of results logged in the console.
You need to update your code like this
func getUserDocuments(_ onSuccess: ((_ thoughts: [Thought] ) -> Void), onFailuer: ((_ error: String) -> Void)) {
var tempThoughts = [Thought]()
db.collection(cUser!.uid).getDocuments() { (querySnapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
onFailuer(err)
} else {
DispatchQueue.main.async {
for document in querySnapshot!.documents {
print("\(document.documentID) => \(document.data())")
let tempThought: Thought = Thought(id: document.get("id") as! String, content: document.get("content") as! String, dateCreated: document.get("timestamp") as! String, isFavorite: (document.get("isFavorite") != nil))
tempThoughts.append(tempThought)
}
print("TEST")
print(tempThoughts)
onSuccess(tempThoughts)
}
}
}
}
user this code
And you can use this function like this
getUserDocuments({ (thoughts) in
// Your logic
}) { (error) in
// error Occured
}

How do I make a nested var update if it exists in Realm, in Swift?

I have an Auth object that has a User object. I store the Auth object because it also has other information (like my access token).
If I log in once, then log out-- no issues. It creates the auth object, which then creates the user object... and logging out deletes the auth object (but keeps the user object) which is fine to me.
However, when I go to log in a second time, it fails because it tries to create the user object again, but the primary key is the same and I get this error:
"Can't set primary key property 'id' to existing value '123123123'"
(123123123 is a sample id)
How do I make it that when I add an Auth object to Realm, it updates the existing user (if exists) instead of trying to create a new one w/ the same primary key?
Thanks!
Auth object:
class Auth: Object, Mappable {
static var currentAuth: Auth? {
set {
let realm = try! Realm()
try! realm.write {
if let oldValue = currentAuth {
realm.delete(oldValue)
}
if let currentAuth = newValue {
realm.add(currentAuth)
}
}
NSNotificationCenter.defaultCenter().postNotificationName("didChangeLogin", object: nil)
}
get {
let realm = try! Realm()
// there should only be 1 or 0
return realm.objects(Auth).first
}
}
dynamic var accessToken: String?
dynamic var user: User?
func mapping(map: Map) {
accessToken <- map["access_token"]
user <- map["user"]
}
// MARK: - Convenience
class func logout() {
currentAuth = nil
}
// MARK: - Required
required init() { super.init() }
required init?(_ map: Map) { super.init() }
required init(value: AnyObject, schema: RLMSchema) { super.init(value: value, schema: schema) }
required init(realm: RLMRealm, schema: RLMObjectSchema) { super.init(realm: realm, schema: schema) }
}
User object:
class User: Base {
dynamic var username: String?
dynamic var bio: String?
override func mapping(map: Map) {
super.mapping(map)
username <- map["username"]
bio <- map["bio"]
}
// MARK: - Requireds
required init() { super.init() }
required init?(_ map: Map) { super.init() }
required init(value: AnyObject, schema: RLMSchema) { super.init(value: value, schema: schema) }
required init(realm: RLMRealm, schema: RLMObjectSchema) { super.init(realm: realm, schema: schema) }
}
^ For reference
It seems that the User's primary key is conflict (Maybe it is defined in Base class?).
Realm doesn't have cascading delete, so the User object is left even deleting the old Auth object.
If you'd like to update when the object that has existing primary key, you should pass true to the update parameter of add(_:, update:) method. However, the Auth class doesn't have a primary key property, so you cannot pass true to the update parameter when adding the Auth object.
There are two ways to solve the problem.
1.
The first way is adding a primary key to the Auth class (Perhaps, accessToken property would be appropriate.). Like the following:
class Auth: Object, Mappable {
...
override class func primaryKey() -> String? {
return "accessToken"
}
...
}
Then, you can pass true to the add(_:, update:).
if let currentAuth = newValue {
realm.add(currentAuth, update: true)
}
2.
The second way is deleting the old User object when deleting old Auth object. Like the following:
static var currentAuth: Auth? {
set {
let realm = try! Realm()
try! realm.write {
if let oldUserValue = currentAuth?.user {
realm.delete(oldUserValue)
}
if let oldValue = currentAuth {
realm.delete(oldValue)
}
if let currentAuth = newValue {
realm.add(currentAuth)
}
}
...

Warning: A long-running operation is being executed on the main thread. try! get data(). Swift

I know that the error comes from try! converyPFFile.getData()
Wondering how to get rid of the error if I don't want to get data in background because if I get data in background, the image cannot be appended to the array. Thanks.
query.findObjectsInBackgroundWithBlock { (objects: [PFObject]?, error: NSError?) -> Void in
for object in objects! {
self.senderArray.append(object.objectForKey("sender") as! String)
self.messageArray.append(object.objectForKey("message") as? String)
if object.objectForKey("photo") != nil {
if let converyPFFile = object.objectForKey("photo") as? PFFile{
let temp = try! converyPFFile.getData()
let image = UIImage(data: temp)
self.photoArray.append(image)
}
} else {
self.photoArray.append(nil)
}
}
// create a chat interface
if self.senderArray[i] == self.userName {
if self.messageArray[i] != nil {
// using scroll view
// create username label
// create message text label
} else {
// using scroll view
// create username label
// create message image
messageImage.image = self.photoArray[i]
}
....
I found this warning is coming from Parse. You can overcome it by using getDataInBackgroundWithBlock and then append to your array within that block. Therefore your code becomes something like (untested and I think I have mis-paired braces):
query.findObjectsInBackgroundWithBlock { (objects: [PFObject]?, error: NSError?) -> Void in
for object in objects! {
self.senderArray.append(object.objectForKey("sender") as! String)
self.messageArray.append(object.objectForKey("message") as? String)
if object.objectForKey("photo") != nil {
if let converyPFFile = object.objectForKey("photo") as? PFFile{
converyPFFile.getDataInBackgroundWithBlock { (data: NSData!, error: NSError!) -> Void in
let image = UIImage(data: data)
self.photoArray.append(image)
}
} else {
self.photoArray.append(nil)
}
}
// create a chat interface
if self.senderArray[i] == self.userName {
if self.messageArray[i] != nil {
// create username label
// create message text label
} else {
// create username label
// create message image
messageImage.image = self.photoArray[i]
}
....
It is possible to execute your task in the background while still making sure that appending to your photo array is done on the main thread.
You simply need to dispatch that particular code to the main thread.
See example below:
query.findObjectsInBackgroundWithBlock { (objects: [PFObject]?, error: NSError?) -> Void in
for object in objects! {
self.senderArray.append(object.objectForKey("sender") as! String)
self.messageArray.append(object.objectForKey("message") as? String)
if object.objectForKey("photo") != nil {
if let converyPFFile = object.objectForKey("photo") as? PFFile{
let temp = try! converyPFFile.getData()
let image = UIImage(data: temp)
// this will cause self.photoArray.append to be executed on the main thread
dispatch_async(dispatch_get_main_queue(),{
self.photoArray.append(image)
})
}
} else {
// this will cause self.photoArray.append to be executed on the main thread
dispatch_async(dispatch_get_main_queue(),{
self.photoArray.append(nil)
})
}
}
// create a chat interface
if self.senderArray[i] == self.userName {
if self.messageArray[i] != nil {
// create username label
// create message text label
} else {
// create username label
// create message image
messageImage.image = self.photoArray[i]
}

Swift array doesn't hold values

I ran into the following problem while trying to build something with Swift. Apparently, the values that I added into an array are not saved pass some point. They are sent just fine with the protocol while the task is running, but after it completes, if I try to see the values in the array, it returns empty.
What am i doing wrong? My guess is that it get deallocated after task finishes. If that is so, is there a way to make it strong? Is there something I should know about this task thingie? Can you please explain to me how this works and what I should do?
Here is the code:
var exchangeArray : ExchangeValues[] = [];
func fetchResult(){
var currenciesOrder = ["EUR", "USD", "GBP", "CHF", "NOK", "SEK", "DKK", "CZK","TRY", "BGN", "MDL", "PLN", "XDR", "XAU", "UAH", "RUB", "RSD","CAD", "AUD", "JPY", "EGP", "BRL","HUF", "MXN","KRW", "CNY","NZD","INR","AED", "ZAR"];
let dateFormat = NSDateFormatter();
dateFormat.dateFormat = "yyyy-MM-dd";
for days in 0..2 {
let daysToSubstract = Double(60*60*24*days);
let date : String = dateFormat.stringFromDate(NSDate().dateByAddingTimeInterval(-daysToSubstract));
var url: NSURL = NSURL(string: "http://openapi.ro/api/exchange/all.json?date=" + date);
var session = NSURLSession.sharedSession();
var task = session.dataTaskWithURL(url, completionHandler: {
(data, response, error) -> Void in
if (response != nil){
var err: NSError?;
if(err?) {
println("request Error \(err!.localizedDescription)");
}
//send the result to protocol
let results = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary;
let temp : NSDictionary = results["rate"] as NSDictionary;
for key in 0..currenciesOrder.count{
for (currencyKey : AnyObject, currencyValue : AnyObject) in temp {
if currenciesOrder[key] as String == currencyKey as String {
let tempExchange = ExchangeValues(currency: currencyKey as? String, value: currencyValue.doubleValue, date:date );
self.exchangeArray.append(tempExchange);
}
}
}
self.delegate?.didReceiveResults(self.exchangeArray);
} else {
println("error: \(error.localizedDescription)");
}
})
task.resume();
}
println("\(exchangeArray.count)");
}
I kind of figured out what the problem is:
The task block returns void, so I think it empties the array after it finishes. The result is to create another function that gets called from the task, where the array works just fine (it gets passed the values while they exist) and any further processing can be done there.
I hope this helps someone. The code is as easy as this:
func sendResults(array : ExchangeValues[]) -> Void{
println("\(exchangeArray.count)"); }
Of course, you can have the function return something if you need to.

Resources