I have a requirement where i have to use string from resources in android to support different languages . Switch case is not taking string as constant from resources. Like R.string.example

So i have to use enums.Need an example to use enums constant using string resources in android and using it in Switch case

In my MainActivity, I have the following function:

public void writefile (FileOutputStream fOut, String fileName, OutputStreamWriter osw, String message){
    try {
        fOut = openFileOutput(fileName, MODE_WORLD_READABLE);
        osw = new OutputStreamWriter(fOut);
        osw.write(message);
        osw.flush();
        osw.close();
    }
    catch (IOException ioe){
        ioe.printStackTrace();
    }
}

My SMS receiver for this app MUST be non-dynamic (no layout), and within my onReceive method, I try to call the function:

writefile(fOut, ib1, osw, message);

My parameters are all ok, but 'writefile' becomes red and 'cannot be resolved.' So I tried changing it to:

MainActivity.writefile(fOut, ib1, osw, message);

But now, 'writefile' is underlined with a static/non-static problem. In order to get rid of this error, I tried making the function static in MainActivity, but then, 'openFileOutput' starts to complain about static/non-static.

I was willing to put the function into my Receiver class too to be called every time from the same class, but functions like 'openFileOutput' cannot be resolved because the Receiver can only extend BroadcastReceiver.

I was also willing to call another activity upon onReceiver and do my work there, but I couldn't find a way to implement that either.

Can anybody please offer me any help on this issue? Thanks in advance.

I have about 229 image assets that I am referring to here. I would like to have a grid of all the images shown in an activity. the images are of places. If a place has not been discovered, I want the picture to be a silhouette of the respective image, and if it has been discovered, I want it to show the actual image.

I don't have silhouettes of my images, and I could do them one by one, but that seems a bit ridiculous.

Is there some android/java property or method I can use to 'black' out the image? Or, is there a tool online I can upload a folder of images to that will black them all out, and I can download a zip folder?

On our Android app we need to detect when users have been providing us with fake locations. Once we disable the fake location app ("Fake GPS"), the Fused Location Provider keeps sending us the old location, but without the mock location key on it.

Is this a known bug? Is there any way to detect if those new locations were from the fake provider?

We are using a Nexus 6P with 6.0.1 to test

Parting from the Android Quickstart Firebase Auth sample, is it ok to do the following in onActivityResult after a successfull Google Sign-In?

@Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == DialogSignInFragment.RC_SIGN_IN) {
        GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
        if (result.isSuccess()) {

            //-------- Is the following call allowed? --------
            Auth.GoogleSignInApi.signOut(mGoogleApiClient);

            GoogleSignInAccount account = result.getSignInAccount();
            firebaseAuthWithGoogleSignInStepTwo(account);
        } else {
            Log.e(TAG, "GOOGLE SIGN IN FAILED: " + result.toString());
        }
    }
}

As far as I know, authenticating to Firebase with a Google account is a two step process.

First you sign in into the Google account to retrieve a token, then you use that token to get the credentials so that you can perform a FirebaseAuth.signInWithCredential() call to ultimately sign into firebase.

Is it necessary for any further Firebase operation to remain signed-in with that Google Sign-In process? I'd say no, since you also don't have to remain signed into Facebook for Firebase to continue working, is this assumption correct?

Are there any negative side-effects to doing this? I want to sign out after a successfull sign-in in order to keep the code cleaner. FYI, the following code does successfully sign into Firebase even after that Auth.GoogleSignInApi.signOut() call.

What are the limitations, ie, how long are those credentials valid after signing out? Long enough to be able to sign into Firebase with them, or will a race condition start on Googles servers?

i am trying to send Data (ID value) from one activity to other but it wouldn't send correct data , i want it to send only ID Value of Clicked Item to next activity , here is my code

public class Order extends AppCompatActivity {

    private ListView lvUsers;
    private ProgressDialog dialog;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sub);
    dialog = new ProgressDialog(this);
    dialog.setIndeterminate(true);
    dialog.setCancelable(false);
    dialog.setMessage("Loading, please wait.....");

    lvUsers = (ListView) findViewById(R.id.lvUsers);
    new JSONTask().execute("http://146.185.178.83/resttest/order");

}

public class JSONTask extends AsyncTask<String, String, List<OrderModel> > {

    @Override
    protected void onPreExecute(){
        super.onPreExecute();
        dialog.show();
    }

    @Override
    protected List<OrderModel> doInBackground(String... params) {
        HttpURLConnection connection = null;
        BufferedReader reader = null;

        try {
            URL url = new URL(params[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();

            InputStream stream = connection.getInputStream();

            reader = new BufferedReader(new InputStreamReader(stream));

            StringBuffer buffer = new StringBuffer();

            String line ="";
            while ((line=reader.readLine()) !=null){
                buffer.append(line);
            }

            String finalJson = buffer.toString();

            JSONArray parentArray = new JSONArray(finalJson);

            List<OrderModel> orderModelList = new ArrayList<>();

            Gson gson = new Gson();
            for (int i = 0; i < parentArray.length(); i++) {
                JSONObject finalObject = parentArray.getJSONObject(i);
                OrderModel orderModel = gson.fromJson(finalObject.toString(), OrderModel.class);
                orderModelList.add(orderModel);
            }
            return orderModelList;

        }catch (MalformedURLException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } finally {
            if(connection !=null) {
                connection.disconnect();
            }
            try {
                if (reader !=null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    @Override
    protected void onPostExecute(List<OrderModel> result) {
        super.onPostExecute(result);
        dialog.dismiss();
        OrderAdapter adapter = new OrderAdapter(getApplicationContext(), R.layout.row_order, result);
        lvUsers.setAdapter(adapter);

    }
}
public class OrderAdapter extends ArrayAdapter {

    public List<OrderModel> orderModelList;
    private int resource;
    private LayoutInflater inflater;
    public OrderAdapter(Context context, int resource, List<OrderModel> objects) {
        super(context, resource, objects);
        orderModelList = objects;
        this.resource = resource;
        inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder holder = null;

        if(convertView == null){
            holder = new ViewHolder();
            convertView=inflater.inflate(resource, null);
            holder.bOrderNo = (Button) convertView.findViewById(R.id.bOrderNo);
            convertView.setTag(holder);
        }else {
            holder = (ViewHolder) convertView.getTag();
        }

        final int orderId = orderModelList.get(position).getId();
        holder.bOrderNo.setText("Order No: " + orderModelList.get(position).getOrderId());
        holder.bOrderNo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent = new Intent(Order.this, OrderSelected.class);
                intent.putExtra("parameter_name", orderId);
                startActivity(intent);
            }
        });
        return convertView;
    }

    class ViewHolder{
        private Button bOrderNo;
    }
}

}

The holder gets executed in loop i guess is why it wouldn't send right Id. How do i get it to send only Id of the clicked orderId

you can check this link to see how json Response looks like http://146.185.178.83/resttest/order

I am creating an application for a boutique. The application should monitor the whatsapp image folder for new images (as a service in the background). When new images arrive (downloaded), the service should read the image and add a 'text' watermark, which shall be the product code of that image, and then save it back in the same file name. Thus when the user opens the image using any application, he shall be able to see the image with product code watermarked in it. The product code shall be a number sequence.

I was thinking writing a service that shall scan the entire whatsapp image folder, and water mark each image. The service should also write some extra metadata as EXIF info, to identify whether an image is already watermarked.

is this possible? How can i do that?

Any help on how to get my recyclerView to stop changing the disabled items on scroll. here is some example code:

@Override
public PlayerSelectRVAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    Context context = parent.getContext();
    LayoutInflater inflater = LayoutInflater.from(context);

    View contactView = inflater.inflate(R.layout....., parent, false);

    ViewHolder viewHolder = new ViewHolder(contactView);
    return viewHolder;
}


@Override
public void onBindViewHolder(PlayerSelectRVAdapter.ViewHolder viewHolder, int position) {
    final Object player = objects.get(position);

    viewHolder.setPlayer(player);
    SetUi(viewHolder);
}


public static class ViewHolder extends RecyclerView.ViewHolder {
    private final View mView;
    private Object player;

    public ViewHolder(View itemView) {
        super(itemView);
        this.mView = itemView;

        mView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (listener != null)
                    listener.onItemClick(mView, getLayoutPosition());
                }
            });
        }
     }
}

Ok, so in my setPlayer method i am also taking the itemView for that holder and setting if its disabled or not. then i call my SetUi to actually do the view set up.

Thing is it all loads correct until i start scrolling and it messes up. In fact eventually everything becomes disabled.

I am a beginner in the Cordova software but I know this topic has already been investigated upon, however none of the other solutions found so far worked.

So basically what I want to do is to display a google map view on an Android app. I am using Cordova, which provides the cordova-plugin-googlemaps that allows me to use google maps services on a native app.

Situation

- Necessary SDK plugins are installed

Google play services is installed. Basically all google plugins present in the SDK manager are installed.


- Created key with Google maps v2 API (Goolge APIs)

Google certificates screenshot

Even after waiting to insert the key in my project past the "5 minutes" Google asks to wait, still nothing.


- Working on iOS but not on Android

Android and iOS

Screenshots of android and ios


- AndroidManifest.xml has API key

Cordova automatically modified the androidManifest.xml and inserted the key (with command: cordova plugin add cordova-plugin-googlemaps --variable API_KEY_FOR_ANDROID="AIz#################################_aE" --variable API_KEY_FOR_IOS="AIz#################################Rns")

        ...

    </activity>

    <meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="AI***********************************aE" />

    <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />

</application>

...

- logcat message of Android device says "Authorization failure"

Error message:

E/Google Maps Android API( 8608): Authorization failure.  Please see https://developers.google.com/maps/documentation/android-api/start for how to correctly set up the map.
E/Google Maps Android API( 8608): In the Google Developer Console (https://console.developers.google.com)
E/Google Maps Android API( 8608): Ensure that the "Google Maps Android API v2" is enabled.
E/Google Maps Android API( 8608): Ensure that the following Android Key exists:
E/Google Maps Android API( 8608):   API Key: AIz#################################_aE
E/Google Maps Android API( 8608):   Android Application (<cert_fingerprint>;<package_name>): 12:################################################C6:F5:41;com.example.mapProj

Authorization failure means there is something wrong with the certificate but nothing seems to be out of place right?



Reinstalling plugins, cleaning caches and creating new projects never worked for me.

I appreciate any help of any kind for this issue. I guess that Cordova can't allow this plugin to be broken on Android so there must be something wrong, it's just that I can't find it

Thanks

I have an app that mutes the phone by using AudioManager and setting ringer mode to silent with this code:

AudioManager audioManager = 
    (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
try {
    audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT)
} catch (Exception e) {
    e.printStackTrace();
}

This works with Android 6, but now with Android 7, I get the following error:

System.err: java.lang.SecurityException: Not allowed to change Do Not Disturb state
System.err: at android.os.Parcel.readException(Parcel.java:1683)
System.err: at android.os.Parcel.readException(Parcel.java:1636)
System.err: at android.media.IAudioService$Stub$Proxy.setRingerModeExternal(IAudioService.java:962)
System.err: at android.media.AudioManager.setRingerMode(AudioManager.java:1022)
System.err: at controllers.SearchResultController.mutePhone(SearchResultController.java:185)

Are there any new permissions I need to ask for to make this work?

I looked through the Android permissions list, but couldn't find any that seemed relevant.

I retrieve state list from my database. I get list in the form of json. I add all state in ArrayList<String>. Now I want to display that complete list of states in AlertDialog using adapter.

But when I set arraylist to adapter and use that adapter in builder.setAdapter(); it displays last item of arraylist i.e only one value from complete arraylist.

I don't know how to do?

below is my code

JSONObject jsonObject = new JSONObject(response.body().string());
Log.d("JSON", String.valueOf(jsonObject));
JSONArray jsonArray = jsonObject.getJSONArray("states");

for(int i=0; i<jsonArray.length(); i++)  {
    stateList = new ArrayList<String>();
    JSONObject jobjstate = jsonArray.getJSONObject(i);

    states = jobjstate.getString("state_name");

    stateList.add(states);
    stateAdapter = new ArrayAdapter<String>(UserRegister.this, android.R.layout.simple_spinner_dropdown_item, stateList);
}

runOnUiThread(new Runnable() {
    @Override
    public void run() {
        AlertDialog.Builder builder = new AlertDialog.Builder(UserRegister.this);

        View customTitle = View.inflate(getApplicationContext(), R.layout.custom_dialog_state, null);
        builder.setCustomTitle(customTitle);

        builder.setAdapter(stateAdapter, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                etregstate.setTextColor(getResources().getColor(R.color.black));
                etregstate.setText(stateList.get(which));
                dialog.dismiss();
            }
        });
        AlertDialog alertDialog = builder.create();
        ListView listView = alertDialog.getListView();
        listView.setDivider(new ColorDrawable(getResources().getColor(R.color.purple)));
        listView.setDividerHeight(2);
        alertDialog.show();
    }
});

I have a RecyclerView that gets touch events. Everything works fine, BUT, when I make Visibility.Visible a LinearLayout (android:clickable="true") above the Recyclerview, and later I make it Visibility.Gone .Then the recyclerView does not gets the touch events. What can I do?

tip_container is the problematic Layout, that swallows RecyclerView touch events when visibility.visible, and even when once shown is visibility.gone.

Thanks

 <?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout

xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/DrawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:fancy="http://schemas.android.com/apk/res-auto"
android:elevation="7dp">



<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">


    <include
        android:id="@+id/tool_bar"
        layout="@layout/tool_bar"
       >
    </include>

    <FrameLayout android:id="@+id/contenedor" android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>


<android.support.v7.widget.RecyclerView
    android:id="@+id/RecyclerView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:background="#ffffff"
    android:scrollbars="vertical">

</android.support.v7.widget.RecyclerView>


<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#313131"
    android:id="@+id/tip_container"
    android:visibility="gone"
    android:layout_margin="0dp"
    android:padding="0dp"

    >
    <ImageView
        android:id="@+id/tip_drawable"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerInside"
        android:src="@drawable/tip_minutos"/>
    <ImageView
        android:id="@+id/tip_close"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:layout_marginRight="10dp"
        android:src="@drawable/cross_close"
        android:scaleType="centerInside"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:clickable="true"
        android:tint="@color/white"
        android:layout_marginTop="40dp"/>

    <mehdi.sakout.fancybuttons.FancyButton
        android:id="@+id/tip_boton_continuar"
        android:layout_width="match_parent"
        android:layout_height="55dp"

        fancy:fb_textSize="14sp"
        android:paddingBottom="8dp"
        android:paddingLeft="20dp"
        android:paddingRight="20dp"
        android:paddingTop="8dp"
        fancy:fb_defaultColor="#00000000"
        fancy:fb_focusColor="@color/BotonVerdeFocus"
        fancy:fb_radius="0dp"
        fancy:fb_borderWidth="1dp"
        fancy:fb_borderColor="#ffffff"
        fancy:fb_text="Continuar"
        fancy:fb_textColor="@color/white"
        android:fontFamily="sans-serif"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginBottom="10dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"

        android:visibility="visible"/>



</RelativeLayout>

I am trying to hide the address bar for both iphone and android (if possible) and have seen multiple threads that used the following code snippet as part of their DNN website by inserting the following into their default.aspx file:

    <%-- Add mobile bookmark buttons --%>   
    <meta name="apple-mobile-web-app-capable" content="yes" />
        <meta name="mobile-web-app-capable" content="yes">

<%-- Set Apple icons. --%>
<asp:placeholder ID="appleIcons" runat="server" />   

        <%-- Set view port for mobile devices. --%>
       <meta name = "viewport" content = "width=device-width" />
        <meta name="viewport" content="width=device-width, minimal-ui">

         <%-- Set Apple icons. --%>
         <link rel="apple-touch-icon" href="/Portals/0/images/apple-touch-icon-114x144.png" />
          <link rel="apple-touch-icon" sizes="72x72" href="/Portals/0/images/apple-touch-icon-114x144.png" />
          <link rel="apple-touch-icon" sizes="114x114" href="/Portals/0/images/apple-touch-icon-114x144.png" />
          <link rel="apple-touch-icon" sizes="144x144" href="/Portals/0/images/apple-touch-icon-114x144.png" />  

         <%-- Remove URL bar on mobile devices. --%>                 
        <script type="application/x-javascript"> 
            addEventListener("load", function() { setTimeout( hideURLbar, 0); }, false); 
            function hideURLbar(){ window.scrollTo(0,1); } 
        </script>

I have tested all related threads on this topic. The above worked on a site previously albeit only on iphone but no longer working for me. Appreciate any comments.

I am trying to use this code

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    NSLog(@"%f",self.view.frame.origin.y);
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.25f];
    CGRect frame = self.view.frame;
    frame.origin.y =frame.origin.y -204;
    [self.view setFrame:frame];
    [UIView commitAnimations];
}


- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.25f];
    CGRect frame = self.view.frame;
    frame.origin.y = frame.origin.y + 204;
    [self.view setFrame:frame];
    [UIView commitAnimations];
}

To move view up when keyboard is present but this results like this: enter image description here

becomes this:

enter image description here

Can't figure out why and if it has to do something with the navbar or constraints.

I am using The Amazing Audio Engine to simply play an audio file, but I find that when the channel starts playing, there is some automatic fade in happening.

You can see the top waveform is the output of my iPad, and the bottom waveform is the actual raw audio file. There is definitely a 30ms microfade being done.

enter image description here

There is nothing doing that within the amazing audio engine library, so it's something internally happening from apple's mixer audio unit. Is there any way to turn off this behavior?

I have an UIScrollView and inside this I have an UILabel. I need to detect tap gesture events for the UILabel. At the moment, it' not working. I am new in xamarin IOS, please help. Thanks in advance.

Here is my Code

UILabel lViewallLabel = new UILabel(new CGRect((View.Bounds.Width / 2) - 20, 270, View.Bounds.Width / 2, 16));
lViewallLabel.Text = "VIEW ALL >>";
lViewallLabel.TextAlignment = UITextAlignment.Right;
lViewallLabel.TextColor = UIColor.White;
lViewallLabel.Font = UIFont.SystemFontOfSize(12f);
lViewallLabel.AdjustsFontSizeToFitWidth = true;
lViewallLabel.UserInteractionEnabled = true;
UITapGestureRecognizer tgrLabel2 = new UITapGestureRecognizer(() =>
       {
             UIAlertView myAlert = new UIAlertView();
             myAlert.AddButton("OK");
             myAlert.Message = "Label was tapped.";
             myAlert.Title = "It worked!";
             myAlert.Show();
        });
lViewallLabel.AddGestureRecognizer(tgrLabel2);
innerView.AddSubview(lViewallLabel);

scrollView.AddSubview(innerView);

I have a simple test (see below). I would like to run the test with like 6 input values. I could create 6 single methods with 6 datasets, or iterate through 6 setups. While putting everything in it's own method would show me a failure more detailed, the second one would have less redundant code.

Which way is the better one?

    func testValueByStringRange_1(){

    let parser = Parser()
    let input = "22016080120160802ZE0000000000000+RP0000000000000+RF0000000000000-"
    let indexFrom = 19
    let indexTo = 31

    let expected = "000000000000"
    let returnString = parser.valueByStringRange(input, indexFrom: indexFrom, indexTo: indexTo)

    XCTAssertEqual(returnString, expected)
}

One reason a profile may be invalid according to Developer.Apple.com is that the certificate is now obsolete. Checking for the cert is covered in this post: Validate certificate and provisioning profile

I am interested more generally, how to test if the profile is now stale. Right now I find out with a very long delay, so it is impossible to decipher the cause of the invalidation. If I could run this command, say each time my build job runs on Jenkins, then I could be better able to failure analyze by noting exactly when the shift occurred from valid to invalid.

I've been trying to use UISegmentedControl as a multiple-choice selection tool. I thought that if I could rotate it 90 degrees (as well as the text inside) and expand the cells, it would be a very fluid tool. However no matter what I try it keeps giving me variations of thisbroken UISegmentedControl

By the way, this is inside a UICollectionView. Here is my code for the UICollectionViewCell

class customCollectionCell: UICollectionViewCell {
@IBOutlet weak var questionLabel: UILabel!
@IBOutlet weak var questionDescriptionLabel: UILabel!
@IBOutlet weak var viewForSegment: UIView!
var segment: CustomSegmentedControl!

func heightForView(text:String, width:CGFloat) -> CGFloat{
    let label:UILabel = UILabel(frame: CGRectMake(0, 0, width, CGFloat.max))
    label.numberOfLines = 0
    label.lineBreakMode = NSLineBreakMode.ByWordWrapping
    label.text = text

    label.sizeToFit()
    return label.frame.height
}

func loadQuestions(choices: [String], pointIndex: [Int]) {
    segment = CustomSegmentedControl(items: choices)
    segment.transform = CGAffineTransformMakeRotation(CGFloat(M_PI / 2.0));
    for view in segment.subviews {
        for sv in view.subviews {
            if sv.isKindOfClass(UILabel){
                let subview: UILabel = sv as! UILabel
                subview.transform = CGAffineTransformMakeRotation(CGFloat(-M_PI / 2.0))
                subview.addConstraint(NSLayoutConstraint(item: subview,
                    attribute: NSLayoutAttribute.Height,
                    relatedBy: NSLayoutRelation.Equal,
                    toItem: nil,
                    attribute:NSLayoutAttribute.NotAnAttribute,
                    multiplier:1,
                    constant: heightForView(subview.text!, width: self.viewForSegment.frame.width)))
                subview.addConstraint(NSLayoutConstraint(item: subview,
                    attribute: NSLayoutAttribute.Width,
                    relatedBy: NSLayoutRelation.Equal,
                    toItem: nil,
                    attribute:NSLayoutAttribute.NotAnAttribute,
                    multiplier:1,
                    constant: self.viewForSegment.frame.width))
            }
        }
    }
    segment.pointIndex = pointIndex
    /*
    self.addConstraint(NSLayoutConstraint(item: segment, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.LeftMargin, multiplier: 1, constant: 0))
    self.addConstraint(NSLayoutConstraint(item: segment, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.BottomMargin, multiplier: 1, constant: 0))
    self.addConstraint(NSLayoutConstraint(item: segment, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.RightMargin, multiplier: 1, constant: 0))
    self.addConstraint(NSLayoutConstraint(item: segment, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: questionDescriptionLabel, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 20))
    segment.frame = CGRect(origin: CGPoint(x: questionLabel.x, y: ), size: segment.systemLayoutSizeFittingSize(UILayoutFittingExpandedSize))
    */

    segment.bounds.size = segment.systemLayoutSizeFittingSize(UILayoutFittingExpandedSize)
    viewForSegment.addSubview(segment)
    viewForSegment.frame.size = viewForSegment.systemLayoutSizeFittingSize(UILayoutFittingExpandedSize)
}

}

I am trying to build an application for users to view Images. For this I use the pixaBay API which returns the following JSON on an API request.

  {
"total": 4692
"totalHits": 500,
"hits": [
    {
        "id": 195893,
        "pageURL": "https://pixabay.com/en/blossom-bloom-flower-yellow-close-195893/",
        "type": "photo",
        "tags": "blossom, bloom, flower",
        "previewURL": "https://pixabay.com/static/uploads/photo/2013/10/15/09/12/flower-195893_150.jpg"
        "https://pixabay.com/get/35bbf209db8dc9f2fa36746403097ae226b796b9e13e39d2_640.jpg",
        "webformatWidth": 640,
        "webformatHeight": 360,
        "imageWidth": 4000,
        "imageHeight": 2250,
        "views": 7671,
        "https://pixabay.com/static/uploads/user/2013/11/05/02-10-23-764_250x250.jpg",
    },
    {
        "id": 14724,
        ...
    },
    ...
]

}

This is how I implemented the code, to take the previewURLs and load the preview Images on cells with a UICollectionView

     import UIKit
   import Alamofire
   import SwiftyJSON

class ViewController: UIViewController , UICollectionViewDataSource{

@IBOutlet weak var collectionView: UICollectionView!

var newImage : UIImage?
var imageURL : NSURL?
var images:[NSIndexPath: UIImage] = [:]

var previewURL : NSURL? = NSURL()


override func viewDidLoad() {
    super.viewDidLoad()
 }



func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 20
}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

  let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! CollectionViewCell

    // MARK : STICKING UP A URL TO EACH CELL

    Alamofire.request(.GET, "https://pixabay.com/api/", parameters: ["key": "31....7f"])
        .responseJSON{ response in
            if let value = response.result.value {


               let hits = JSON(value)["hits"]

                if let previewString = hits[indexPath.row]["previewURL"].rawString(){

                    self.previewURL = NSURL(string: previewString)!

              } else{   print("Error : A previewURL wasn't found.")

                }
            }

    // MARK : HOOKING UP THE IMAGEURL WITH A CELL
            cell.imageView.image = nil //or the placeholder image

            if let img = self.images[indexPath] {
                print("\(img) : \(indexPath)")
                cell.imageView.image = img

            } else {
               self.downloadImage({ (image) in

                    dispatch_async(dispatch_get_main_queue(), {
                        if let img = image {
                            self.images[indexPath] = img

                        } else {
                            print("Error!")
                        }
                    })

                })
            }
        }
  return cell
}


func downloadImage(completion: (UIImage?)->Void) {



            if self.previewURL != nil {

                let session = NSURLSession.sharedSession()
                let request = NSURLRequest(URL: previewURL!)
                let task = session.dataTaskWithRequest(request) {data, response, downloadError in

                if let imageData = data  {
                self.newImage = UIImage(data: imageData)
                completion(self.newImage)
            } else {
                completion(nil)
            }
        }
        task.resume()
    } else {
        completion(nil)
       }
    }


  }

How should I modify this code so as to load and display the images on a collectionView quickly and sequentially(i.e. one image downloaded and then displayed rather than all downloaded and displayed collectively) ? This implementation takes a heck of a lot of time.

This question already has an answer here:

I can't figure out why am I getting this error while submitting for preview in itunesconnect, the error itself is unhelpful.

itunesconnect