Alamofire release memory in large number of requests

493 views Asked by At

I have to perform a large number of POST requests (above 150) and each requests holds a significant amount of data (about 2-4Mb).

I am performing such requests in a for-in loop like this:

    @IBAction func synchToServer(sender: AnyObject) {

    var GlobalUserInitiatedQueue: dispatch_queue_t {
        return dispatch_get_global_queue(Int(QOS_CLASS_USER_INITIATED.value), 0)
    }

    dispatch_async(GlobalUserInitiatedQueue) {

        var serviceGroup = dispatch_group_create()

        var fetchRequest = NSFetchRequest(entityName: "Biography")
        let predicate = NSPredicate(format: "synchronization == nil")
        fetchRequest.predicate = predicate

        if let fetchResults = managedObjectContext!.executeFetchRequest(fetchRequest, error: nil) as? [Biography] {  //This pulls around 150-200 results
            var total = 0
            for l in fetchResults {  //This is where all the requests happen....

                var apiURL = getAppSetting("apiurl") ?? ""  //This variable comes from app settings, global method
                let apikey = getAppSetting("api_key") ?? "" //This variable comes from app settings, global method

                dispatch_group_enter(serviceGroup)
                //In this request l.getJSON returns the data from the entoty as a JSON object
                request(Method.POST, apiURL + "api/biography/" + apikey, parameters: l.getJSON(l), encoding: ParameterEncoding.JSON)
                    .validate(statusCode: [200])
                    .validate(contentType: ["application/json"])
                    .responseJSON{(req,response,data,error) in

                            var json = JSON(data!)

                            l.synch_status = json["status"].stringValue
                            l.synch_message = json["description"].stringValue
                            l.synchronization = NSDate()

                            var err: NSError?

                            if(!managedObjectContext!.save(&err)) {
                                println(err?.localizedDescription)
                            }

                        dispatch_group_leave(serviceGroup)
                }

                total++

                if((total % 10) == 0) {
                    //This waits for the requests to finish in groups of 10 maximum
                    dispatch_group_wait(serviceGroup, DISPATCH_TIME_FOREVER)
                }
            }

            //this waits for the reminder of requests
            dispatch_group_wait(serviceGroup, DISPATCH_TIME_FOREVER)
        }            
    }        
}

However, this makes the memory usage go up and up with every request until it eventually makes the application crash. Is there a way to tell alamofire to release memory of already finished requests ?

0

There are 0 answers