I want some assistance in being able to combine SharedPreferences with getPhotos I have selected. I am new with SharedPreferences and kind of not understand how it works.

So I made a SharedPreferencesManager:

public class SharedPreferencesManager {

    private static final String APP_PREFS = "AppPrefsFile";
    private static final String  PICK_IMAGE_MULTIPLE = "PickImageMultiple";

    private SharedPreferences sharedPrefs;
    private static SharedPreferencesManager instance;

    private SharedPreferencesManager(Context context) {
        sharedPrefs = context.getApplicationContext().getSharedPreferences(APP_PREFS, MODE_PRIVATE);

    public static synchronized SharedPreferencesManager getInstance(Context context){
        if(instance == null)
            instance = new SharedPreferencesManager(context);

        return instance;

    /* public int increaseClickCount() {
        int clickCount = sharedPrefs.getInt(NUMBER_OF_CLICKS, 0);
        SharedPreferences.Editor editor = sharedPrefs.edit();
        editor.putInt(NUMBER_OF_CLICKS, clickCount);
        return clickCount;
    } */

    public void putPhotos() {
        Intent intent = new Intent();
        //intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
        SharedPreferences.Editor editor = sharedPrefs.edit();

    public void getPhotos(){
         sharedPrefs.getInt(PICK_IMAGE_MULTIPLE, 0);

What I want to do is keep all selected photos stored in shared preferences so that everytime I open the Glide it will show all selected photos. But it doesn't like the imageUri = prefManager.getPhotos());

public class PhotosGallery extends AppCompatActivity {

    // Used to show glide load image.
    ImageView photoGallery;
    Uri imageUri;

    protected void onCreate(Bundle savedInstanceState) {

        SharedPreferencesManager prefManager = SharedPreferencesManager.getInstance(PhotosGallery.this);

        photoGallery = findViewById(R.id.photo_gallery);

        if (getIntent() != null) {             
            imageUri = prefManager.getPhotos());
            Toast.makeText(PhotosGallery.this, "There are no images displayed", Toast.LENGTH_LONG).show();


Can I have a little help on refactoring the SharedPreferences please?

I have a kind of to-do app with MySQL service and Retrofit. My recyclerview item is a linear layout with horizontal orientation. Its left to right (image-name-status icon).

I fetch a list from server but user may check each of them as "to-do" or "done" For example;

1- Eat

2- Drink

3- Sleep

If user didn't check any of them as "to-do" or "done". I will show "+" icon at the right of recyclerview item, but if user check one or some of hem as "to-do" or "done", then I should show them you've check this as "to-do" etc.

I control user status with this;

Call<Response_Success> fetchItemStatus(@Path("user_id") String userId, @Path("list_id") String listId);

I've tried to do it for each item and after setting adapter, but couldn't make it. Do you have any good suggestions?

I am trying to implement a BottomAppBar into my app and can't make the FAB or BottomAppBar display at the bottom. Here is my layout:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"




However, this is what is being shown in the emulator:


How do I align it at the bottom?

I have a service that draws an overlay view over the system. It is an utility bar. When user clicks it, it shows up. My problem is that I don't want it showing up when user click, but when user swipe it. I have a logic that can distinguish a click from an drag/swipe using onTouchListener.

The problem is: when user click it, I want to ignore the touch and let the android system consumes it. When user swipe, I want to consume the event and dont let android consume it, because I will make my utility bar show up.

How to achieve this? I am on API 25(android N).

Despite this being a simple question I cannot find the answer on google or stackoverflow.

When I use the following code I get this result //com.android.externalstorage.documents/tree/primary:Podcasts

var intent = new Intent(Intent.ActionOpenDocumentTree);
intent.PutExtra("android.content.extra.SHOW_ADVANCED", true);
intent.PutExtra("android.content.extra.FANCY", true);
intent.PutExtra("android.content.extra.SHOW_FILESIZE", true);

Can you help me understand the parts of my result? I am trying to use that path to save a file but it neither saves nor throws an error (READ_EXTERNAL_STORAGE and WRITE_EXTERNAL_STORAGE are enabled).

I am unable to setup Navigation component with com.google.android.material.bottomnavigation.BottomNavigationView it is giving an error.

enter image description here

Here is the code that I am trying to use

 // Setup bottom navigation view

when I open the NavigationUI class, I note that it just accept the old android.support.design.widget.BottomNavigationView but I want to use the new one com.google.android.material.bottomnavigation.BottomNavigationView class. Any idea about it? thanks in advanced.

New android developer realizing things are much harder todo then in a swift environment... all I need is to load images into image view not on a button click but when the user loads the view.

I've found this

URL url = new URL("http://host/theimage.jpg");
URLConnection conn = url.openConnection();
InputStream in = conn.getInputStream();

but not sure how to implement into

public class MessagesFragment extends Fragment {

public MessagesFragment() {
    // Required empty public constructor

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_messages, container, false);



I have not found a working solution at all... I've searched for a few hours now. any help with this nightmare would be greatly appreciated.

I have a GridView that has exactly 4 children. This will never ever change, and I will assign them in onCreate every time. They aren't scrollable because they are so few. Is there any reason to use RecyclerView over GridView or GridLayout here? I know it's better optimized when you need to scroll, but does it even matter if I use RecyclerView, GridView or GridLayout if I will have a number of items that will never go off the screen?

I tried to implement a left side panel, how ever when I implement, it seems that it won't show anything on aside from the container.

Here is my code below:

override func viewDidLoad() {
    initCenter(screen: showVC)

func initCenter(screen: ShowWhichVC) {
    var presetingController: UIViewController
    showVC = screen

    if dashboardVC == nil {
        dashboardVC = UIStoryboard.dashboardController()
        dashboardVC.delegate = self
    presetingController = dashboardVC
    if let con = centerController {
    centerController = presetingController
    centerController.didMove(toParentViewController: self)

private extension UIStoryboard {

    class func mainStoryboard() -> UIStoryboard {
        return UIStoryboard(name: "Main", bundle: Bundle.main)

    class func leftPanelController() -> LeftPanelController? {
        return mainStoryboard().instantiateViewController(withIdentifier: "LeftPanelController") as? LeftPanelController

    class func dashboardController() -> DashboardController? {
        return mainStoryboard().instantiateViewController(withIdentifier: "DashboardController") as? DashboardController

Note: DashboardController and LeftPanelController UI are written programmatically, does this something to do with it? Thanks!

Update GMS

2018-06-24 02:05:46.791965+0800 Pegasus[32657:577667] Google Maps SDK for iOS and Google Places API for iOS version: 2.7.30514.0 2018-06-24 02:05:46.808461+0800 Pegasus[32657:577704] TIC Read Status [2:0x0]: 1:57 2018-06-24 02:05:46.808596+0800 Pegasus[32657:577704] TIC Read Status [2:0x0]: 1:57

I think now it has something to do with the GMSMapview

I am currently looking at using a UICollectionViewController for a screen. However, I have an image that I want to place at the top of the screen and then a UICollectionView with cells containing textfields.

So my question is :

Can I use the UICollectionViewController and move the UICollectionView down underneath the image and allow the controller to handle the keyboard ?


Is it best to use a standard ViewController and add a UICollectionView as a subview and handle the keyboard myself ?

I have a realmService singleton that's using the following code. However it's not been called from the homeController when I request it.

var realmService = RealmService.shared.realm

class RealmService {

static let shared = RealmService()

lazy var realm: Realm = {
    let realm = try! Realm(configuration: config)
    print("Realm set up")
    return realm

lazy private var realmURL: URL = {
    let appDir = try FileManager.default.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
    let url = appDir.appendingPathComponent("TEST.realm")
    return url

lazy private var config: Realm.Configuration = {
    return Realm.Configuration(
        fileURL: self.realmURL,
        inMemoryIdentifier: nil,
        syncConfiguration: nil,
        encryptionKey: nil,
        readOnly: false,
        schemaVersion: 1,
        migrationBlock: nil,
        deleteRealmIfMigrationNeeded: false,
        objectTypes: nil

I get no print statements when a model calls this method like:

    print("Calling realm service")
    if let profile = realmService.objects(Profile.self).filter(predicate).last {}

Not sure if something is missing?


EDIT: Removed external methods and extension calls to simplify the question.

I have a core data singleton class like this :

  class CoreDataUtil {
    static let shared = CoreDataUtil()
    var  container:NSPersistentContainer? = AppDelegate().persistentContainer
    var mainContext:NSManagedObjectContext? = AppDelegate().persistentContainer.viewContext
    var backGroundContext: NSManagedObjectContext? = AppDelegate().persistentContainer.newBackgroundContext()

    init() {

    func setup(){
      mainContext?.mergePolicy =  NSMergeByPropertyObjectTrumpMergePolicy
      backGroundContext?.mergePolicy =  NSMergeByPropertyObjectTrumpMergePolicy

    func getMainContext() -> NSManagedObjectContext {
      let context = CoreDataUtil.shared.mainContext
    return context!

    func getBackgroundContext() -> NSManagedObjectContext {
      let context = CoreDataUtil.shared.backGroundContext
    return context!

    func save()  {
      do {
          try backGroundContext?.save()
      catch {
          print("Error while saving->",error)

Also, I have persistentContainer code in my APpDelegate as follows:

lazy var persistentContainer: NSPersistentContainer = {
     The persistent container for the application. This implementation
     creates and returns a container, having loaded the store for the
     application to it. This property is optional since there are legitimate
     error conditions that could cause the creation of the store to fail.
    let container = NSPersistentContainer(name: "CoreDataAlamo")
    let urlStore = Bundle.main.url(forResource: "CoreDataAlamo", withExtension: "momd")
    let storeDirectory = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first!
    let url = storeDirectory.appendingPathComponent("CoreDataAlamo.momd")
    let description = NSPersistentStoreDescription.init(url:url)
    description.shouldInferMappingModelAutomatically = true
    description.shouldMigrateStoreAutomatically = true
    container.persistentStoreDescriptions = [description]

    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error as NSError? {
            // Replace this implementation with code to handle the error appropriately.
            // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

             Typical reasons for an error here include:
             * The parent directory does not exist, cannot be created, or disallows writing.
             * The persistent store is not accessible, due to permissions or data protection when the device is locked.
             * The device is out of space.
             * The store could not be migrated to the current model version.
             Check the error message to determine what the actual problem was.
            fatalError("Unresolved error \(error), \(error.userInfo)")
    return container

Now, I am using Alamofire object mapper to save in context(using CoreDataUtil) and I don't what a doing wrong but every time I try to fetch from Core Data(using CoreDataUtil), it returns 0 elements. Please help.

I have decodes JSON value into object. The object looks as expected, but when I try to access it's property.

enter image description here

let jsonData = try JSONSerialization.data(withJSONObject: JSON, options: [])
let decoder = JSONDecoder()
let doctor = try! decoder.decode(Doctor.self, from: jsonData)
let txt = "\(doctor.title). \(doctor.firstName) \(doctor.lastName)" // Runtime crash: (Thread 1: EXC_BAD_ACCESS (code=1, address=0x40))

Runtime crash: (Thread 1: EXC_BAD_ACCESS (code=1, address=0x40))

I wrote code for trace feature using TTL ping. Here example IPv6 ping implementation. iOS trace with IPv4 sockets
I'm trying port this code for compatibility with IPv6 protocol but get error when creating send_socket

send_sock = socket(AF_INET6, SOCK_DGRAM, IPPROTO_IPV6) < 0 return -1.

When i'm trying create send_socket with param IPPROTO_IP this error gone but sento not work. What's wrong? Please advise. Thanks.

+ (NSString *)make6Trace:(const char *)address :(int)ttl_t :(int)timeout
    struct hostent *host_entry = gethostbyname2(address, AF_INET6);
    NSLog(@"make6Trace: %s", host_entry->h_name);

    if(host_entry == nil || host_entry->h_addr_list == 0)
        NSLog(@"make6Trace addr error ");
        return nil;

    char *ip_addr = inet_ntoa(*((struct in_addr *)host_entry->h_addr_list[0]));
    struct sockaddr_in6 destination, fromAddr;
    int recv_sock;
    int send_sock;

    if((recv_sock = socket(AF_INET6, SOCK_DGRAM, IPPROTO_ICMPV6)) < 0)
        NSLog(@"make6Trace recv_sock error ");
        return nil;

    if((send_sock = socket(AF_INET6, SOCK_DGRAM, IPPROTO_IPV6)) < 0)
        NSLog(@"make6Trace send_sock error ");
        return nil;

    int ttl = (int)ttl_t;

    struct in6_addr ipv6data;
    inet_pton(AF_INET6, ip_addr, &ipv6data);

    memset(&destination, 0, sizeof(destination));
    destination.sin6_family = AF_INET6;
    destination.sin6_addr = ipv6data;
    destination.sin6_port = htons(33434);

    struct timeval tv;
    tv.tv_sec = timeout / 1000;
    tv.tv_usec = (timeout % 1000) * 1000;

    if(setsockopt(recv_sock, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(struct timeval)) < 0)
        NSLog(@"make6Trace recv_sock setup error");
        return nil;

    NSTimeInterval timeInSeconds = [[NSDate date] timeIntervalSince1970];
    NSString *timestamp = [NSString stringWithFormat:@"%f", timeInSeconds];
    const char *cmsg = [timestamp UTF8String];
    socklen_t n = sizeof(fromAddr);
    int buffer_size = BUFFER_SIZE;
    void * buffer;
    buffer = malloc(buffer_size);
    memset(&fromAddr, 0, sizeof(fromAddr));

    if(setsockopt(send_sock, IPPROTO_IPV6, IP_TTL, &ttl, sizeof(ttl)) < 0)
        NSLog(@"make6Trace send_sock setup error");
        return nil;

    if(sendto(send_sock, cmsg, sizeof(cmsg), 0, (struct sockaddr *) &destination,sizeof(destination)) != sizeof(cmsg))
        NSLog(@"make6Trace sendto error");
        return nil;

    ssize_t bytesRead = recvfrom(recv_sock, buffer, buffer_size, 0, (struct sockaddr *)&fromAddr, &n);

    if(setsockopt(recv_sock, SOL_SOCKET, SO_RCVBUF, &buffer_size, sizeof(buffer_size)) < 0)
        NSLog(@"make6Trace recv_sock setup error(2)");
        return nil;

    NSString *result = nil;

    if(bytesRead > 0)
        NSLog(@"make6Trace letsgo");
        char display[INET_ADDRSTRLEN]= {0};
        inet_ntop(AF_INET6, &fromAddr.sin6_addr, display, sizeof (display));
        //@"Received packet from%s for TTL=%d\n";//,display;
        result = [NSString stringWithCString:display encoding:NSUTF8StringEncoding];

    return nil;

The basic table shows the results correctly - it work properly.

I have a problem with a table that shows the search results, always returns a white page. (no results) The problem may be two tables in one controller?

What am I doing wrong?

class SearchMagazineViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchResultsUpdating {

    @IBOutlet var tableView: UITableView!
    var resultsController: UITableViewController!
    var searchController: UISearchController!
    var searchMagazines: [Magazine]?
    var latestPub = [Magazine]()

    func updateSearchResults(for searchController: UISearchController) {
        let searchText = searchController.searchBar.text!
        if searchText.count > 0 {
            self.searchMagazines = CoreDataHandler.searchMagazine(query: searchText, scope: 0)

    override func viewDidLoad() {

        tableView.delegate = self
        tableView.dataSource = self

        latestPub = CoreDataHandler.latestMagazines() ?? [Magazine]()

        resultsController = UITableViewController(style: .plain)
        resultsController.tableView.register(UINib(nibName: "searchCell", bundle: nil), forCellReuseIdentifier: "searchCell")
        resultsController.tableView.dataSource = self
        resultsController.tableView.delegate = self

        searchController = UISearchController(searchResultsController: resultsController)
        searchController.delegate = self
        searchController.searchResultsUpdater = self
        searchController.hidesNavigationBarDuringPresentation = true

        navigationItem.searchController = searchController

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if tableView == self.resultsController {
            return searchMagazines?.count ?? 0
            return latestPub.count

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if tableView == self.resultsController {
            let cell = tableView.dequeueReusableCell(withIdentifier: "searchCell", for: indexPath) as! SearchCell
            let item = searchMagazines![indexPath.row]
            cell.cat.text = TitleReturn(id: item.cat)
            return cell
            guard let cell = tableView.dequeueReusableCell(withIdentifier: "SearchCell") as? SearchTableViewCell else { return UITableViewCell() }
            cell.title.text = latestPub[indexPath.row].title
            return cell

I am hitting a web service url 10 times and getting the response. I am using Alamofire and SwiftyJSON. This is my controller code

class ViewController: UIViewController {

    let dispatchGroup = DispatchGroup()

    var weatherServiceURL = "http://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b6907d289e10d714a6e88b30761fae22"

    override func viewDidLoad() {

    func start() {
        dispatchGroup.notify(queue: .main) {
            print("All services complete")

    func weatherService() {
        for i in 1...10 {
            APIManager.apiGet(serviceName: self.weatherServiceURL, parameters: ["counter":i]) { (response:JSON?, error:NSError?, count:Int) in
                if let error = error {
                guard let response = response else { return }
                print("\n\(response) \n\(count) response\n")

This is my Service Handler class code

class APIManager: NSObject {

    class func apiGet(serviceName:String,parameters: [String:Any]?, completionHandler: @escaping (JSON?, NSError?, Int) -> ()) {
        Alamofire.request(serviceName, method: .get, parameters: nil, encoding: URLEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in

            switch(response.result) {
            case .success(_):
                if let data = response.result.value{
                    let json = JSON(data)
                    completionHandler(json,nil, parameters!["counter"] as! Int)

            case .failure(_):
                completionHandler(nil,response.result.error as NSError?, parameters!["counter"] as! Int)

I am sending a counter key with the index of for loop just to keep the track of response of which index is coming back. But the response is not coming in serial order. We can expect 3rd response before the 2nd and 1st response. This is because the API call with APIManager.apiGet function call is asynchronous and is escaping and therefore continuing the for loop.

Also I used the dispatchQueue

let dispatchQueue = DispatchQueue(label: "com.test.Queue", qos: .userInteractive)

and converted the function as:

func weatherService() {
    for i in 1...10 {
        dispatchQueue.async {
            APIManager.apiGet(serviceName: self.weatherServiceURL, parameters: ["counter":i]) { (response:JSON?, error:NSError?, count:Int) in
                if let error = error {
                guard let response = response else { return }
                print("\n\(response) \n\(count) response\n")

Same result as the service calling code is asynchronous. If we make

dispatchQueue.sync {
   //service call 

then also we will not get the response in serial order since the networking call in async and dispatchQueue assumes the task is completed.

Condition is to hit the service in async manner only without freezing the UI. If I hit the service is synchronous manner, then I get my desired result. But blocking main thread is not at all acceptable.

I can manage this thing using array or some global bool variables, but I don't want to use them. Is there any other way I can get response in serial order in which it is called? Any help or hint is appreciated.

Can any one tell me how to push one ViewController multiple times? I was using the same code and logic with class view controllers in my project. In between I have to push the same controller again and again and retain values of previous controllers when popping the view controller.

Push same view controller multiple times is ok (working) but when I pop same hierarchy then controller values replaced or mixed.

Can any one tell me how to do this with same class view controllers? I don't want to make multiple view controller files for same code.

I am using fastlane to deploy beta versions of my react-native app to TestFlight. I followed a tutorial which advise to disable Automatic Signing in Xcode and use fastlane match method: it is working great. (Fastlane tutorial)

What I would like to do now is debugging my app on a my own local device:
I tried doing it from Xcode but I am getting this error: xcode error

I also installed ios-deploy and tried react-native run-ios --device command which gives me no error but the app is not appearing on my device. terminal-screeshot

I'm trying to create an app that allows the user to select one or multiple videos, flips the 180° and saves it. I can't seem to find how to do this. Everything online seems in reference to photos, not videos.

I have a bomb spawner in GameScene.swift that adds SKShapeNodes to the Scene. Each SKShapeNode is a physics object that falls and has the name set to "bomb". I want to detect when the user touches these nodes (mid-fall using touchesBegan), but it doesn't work. What am I doing wrong?

// Bomb Spawner Function
func spawnBomb() {
    let bombHeight = 80
    let bomgWidth = 40
    // Define Bomb
    let bomb = SKShapeNode(rectOf: CGSize(width: bomgWidth,
                                          height: bombHeight))
    bomb.name = "bomb"
    bomb.zPosition = 10
    bomb.isUserInteractionEnabled = true
    bomb.position = CGPoint(x: size.width / 2, y:  size.height / 2)
    bomb.fillColor = SKColor.blue
    // Add Physics Body
    bomb.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: bomgWidth,
                                                         height: bombHeight))
    // Determine Random Position
    let randomPosition = abs(CGFloat(random.nextInt()).truncatingRemainder(dividingBy: size.width))
    bomb.position = CGPoint(x: randomPosition, y: size.height)
    // Add Category BitMask
    bomb.physicsBody?.categoryBitMask = BombCategory
    bomb.physicsBody?.contactTestBitMask = WorldFrameCategory
    // Add to the scene


Touch Detection

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch:UITouch = touches.first!
    let positionInScene = touch.location(in: self)
    let touchedNode = self.atPoint(positionInScene)

    if let name = touchedNode.name
        if name == "bomb"
            print("bomb Touched")

I tried all previous answers before but none worked for me. I maybe know the problem and the error is misleading I guess. I am trying to make api request to a server which is https but does not have SSL. Also the apis work only through VPN. So I am disabling SSL verification and everywhere it works fine except a real iOS device like a simulator, postman, android, mac.

What leads I get so far is :

  • DNS Pollution - I tried many times on many devices it never works. If it is DNS how it is working on other android and mac.
  • VPN Tunneling - I saw the release logs of VPN software this exact error was a bug but which is fixed now. Still I am using their app I tried my mac internet with the VPN on iPhone still same error.

The error literally seems like to me is with my code or something logical which needs to be done on iOS to actually work on real device for security(if it is there).

So here I'll share the implementation which made it work on simulator so far (prior to which I was getting same error on simulator).

I am implemented URLSessionDelegate to my router class and allowed arbitrary loads in info.plist. So all are fine url, request etc.

 func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
    completionHandler(.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!))

Before making request:

let config = URLSessionConfiguration.default
let session = URLSession(configuration: config, delegate: self, delegateQueue: .main)