Understanding the Order of Asynchronous Processing

Asked 2 years ago, Updated 2 years ago, 134 views

Using AWS dynamoDB, you bring the URL of the image in the loadUser() database, download the image with downloadImage(), and add it to the scrollView with addImage().
However, if you look at the downloaded order (loadCounter) in downloadImage(),
0
2
1
and so on, but not in order.
Where should I change to download asynchronously in order?Please.

import UIKit
import AWSCore
import AWSS3
import AWSDynamoDB

class LoadViewController: UIViewController, UINavigationControllerDelegate, UIScrollViewDelegate{


    var loadImages: UIImage = [ ]
    varloadItems: DDBTableRow = [ ]

    var userId—String?
    varuserName —String?
    varpagnatedOutput—AWSDynamoDBPagnifiedOutput?

    @IBOutlet weak var scrollView: UIScrollView!

    let defaults = NSUserDefaults.standardUserDefaults()

    override func viewDidLoad(){
        super.viewDidLoad()

        self.scrollView.delegate=self

        self.userName=defaults.stringForKey("userName")
        self.userId=defaults.stringForKey("userId")


        loadUser()

    }
    override funcdidReceiveMemoryWarning(){
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    funcaddImage (image:UIImage)
    {
        let weight = self.scrollView.frame.height
        let width = self.scrollView.frame.width

        loadImages.append(image)
        let myImageView= UIImageView()
        myImageView.frame = CGRectMake (width*CGFloat(loadImages.count-1), 0, width, weight)
        myImageView.image=image
        myImageView.contentMode=.ScaleAspectFit
        scrollView.addSubview(myImageView)
        scrollView.contentSize=CGSizeMake(width*CGFloat(loadImages.count), weight)

    }



    funcloadUser()
    {
        let dynamoDBObjectMapper = AWSDynamoDBObjectMapper.defaultDynamoDBObjectMapper()

        letqueryExpression= AWSDynamoDBQueryExpression()
        queryExpression.hashKeyValues=userId
        queryExpression.scanIndexForward=false
        var loadCounter: Int=0
        dynamoDBObjectMapper.query(DDBTableRow.self, expression:queryExpression).continueWithExecutor(AWSExecutor.mainThreadExecutor(), withBlock:{(task:AWSTask!) ->AnyObject!in
            if(task.error!=nil){
                print("Error:\(task.error)")

            } else{
                if(task.result!=nil){
                    self.pagnifiedOutput=task.result as?AWSDynamoDBPagnifiedOutput

                    US>for item in (self.pagnifiedOutput?.items)!
                    {
                        lettableRow=item as!DDBTableRow

                        print(tableRow.Date)
                        self.downloadImage(tableRow.ImageURL!, loadCounter:loadCounter)
                        self.loadItems.append(tableRow)
                        loadCounter+=1

                    }
                }
                self.performSegueWithIdentifier("unwindToMainSegue", sender:self)
            }
            return nil
        })
    }

    func downloadImage(S3 DownloadKeyName: String, loadCounter:Int) {

        var completionHandler—AWSS3TransferUtilityDownloadCompletionHandlerBlock?

        let queue —dispatch_queue_t =dispatch_queue_create("com.gologo13.gcd", DISPATCH_QUUEUE_SERIAL)

        let expression = AWSS3 TransferUtilityDownloadExpression()
                expression.downloadProgress={(task:AWSS3TransferUtilityTask, bytesSent:Int64, totalBytesSent:Int64, totalBytesExpectedToSend:Int64)in
                    dispatch_async(dispatch_get_main_queue(), {
                        let progress=Float(totalBytesSent)/Float(totalBytesExpectedToSend)
                        NSLog ("Progress is: %f", progress)
                    })
                }


        completionHandler={(task, location, data, error) ->Void in
            dispatch_async(dispatch_get_main_queue(), {
                if(error)!=nil){
                    NSLog ("Failed with error")
                    NSLog("Error: %@", error!)
                }
                else{
                    print(Success)
                    self.addImage(UIImage(data:data!)!)
                    // LoadCounter Debugging
                    print(loadCounter)
                    // LoadCounter does not output values in order
                }
            })
        }

        let transferUtility = AWSS3TransferUtility.defaultS3TransferUtility()

        transferUtility.downloadToURL(nil, bucket:S3BucketName, key:S3DownloadKeyName, expression:expression, completionHander:completionHandler).continueWithBlock{(task)->AnyObject!in
            iflet error=task.error{
                NSLog("Error: %@", error.localizedDescription);
                //  self.statusLabel.text="Failed"
            }
            iflet exception=task.exception{
                NSLog("Exception: %@", exception.description);
                //  self.statusLabel.text="Failed"
            }
            iflet_=task.result{
                //    self.statusLabel.text="Starting Download"
                NSLog("Download Starting!")
                // Something with uploadTask.
            }
            return nil;
        }
    }

}

ios swift objective-c xcode swift2

2022-09-30 21:14

2 Answers

Obtained data

for (vari=0; i<image_list.length;i++) {
image.src=url[i];
}

i of
Why don't you sort it?


2022-09-30 21:14

Instead of adding an image to the end of an array in .addImage, why don't you redraw the array with insert:image, atIndex:loadCounter?


2022-09-30 21:14

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.