Pretty new to android world, I am having an issue playing audio when clicking a button. The interesting/weird aspect of it is that same code works on my mainactivity but not on secondactivity that I have set up. I am using the same exact code that works on mainactivity. I used that code on mainactivity just to test it, keep in mind no media player has been declared or defined in mainactivity. I did that just to test to see if code works.

Here is my xml:

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_marginTop="15sp"
    android:layout_marginBottom="15sp" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="press button to play audio"
        android:textSize="40sp"
        android:textColor="#ffff"
        android:fontFamily="cursive"
        android:textStyle="bold"
        android:layout_marginRight="10dp"
        android:layout_marginLeft="10dp"

        />


</LinearLayout>
<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_marginBottom="10sp"
    android:layout_gravity="center"

    >


    <Button
        android:id="@+id/AudioButton"
        android:layout_width="wrap_content"
        android:layout_height="50sp"
        android:text="play"
        android:textSize="22sp"
        android:textColor="#ffff"
        android:layout_marginRight="10dp"




        />

</LinearLayout>

Here is JAVA:

package nameiscleared;

import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;


public class SecondActivity extends AppCompatActivity {



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_second);

    Button start = (Button) findViewById(R.id.AudioButton);




    start.setOnClickListener(new View.OnClickListener() {
        MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.audioname);

        @Override
        public void onClick(View view) {


            mp.start();
        }
    });
 }
 }

I had error when build my code on android device. its the error report

FATAL EXCEPTION: AsyncTask #1 Process: com.example.guntu, PID: 1248 java.lang.RuntimeException: An error occured while executing doInBackground() at android.os.AsyncTask$3.done(AsyncTask.java:304) at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355) at java.util.concurrent.FutureTask.setException(FutureTask.java:222) at java.util.concurrent.FutureTask.run(FutureTask.java:242) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) at java.lang.Thread.run(Thread.java:818) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'org.json.JSONArray org.json.JSONObject.getJSONArray(java.lang.String)' on a null object reference at com.example.guntu.List$DownloadJSON.doInBackground(List.java:74) at com.example.guntu.List$DownloadJSON.doInBackground(List.java:49) at android.os.AsyncTask$2.call(AsyncTask.java:292) at java.util.concurrent.FutureTask.run(FutureTask.java:237) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)  at java.lang.Thread.run(Thread.java:818)  09-06 07:37:48.656 1248-1248/com.example.guntu E/WindowManager: android.view.WindowLeaked: Activity com.example.guntu.List has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{35557537 V.E..... R......D 0,0-684,322} that was originally added here at android.view.ViewRootImpl.(ViewRootImpl.java:364) at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:271) at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:85) at android.app.Dialog.show(Dialog.java:298) at com.example.guntu.List$DownloadJSON.onPreExecute(List.java:62) at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:591) at android.os.AsyncTask.execute(AsyncTask.java:539) at com.example.guntu.List.onCreate(List.java:44) at android.app.Activity.performCreate(Activity.java:6033) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2288) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2397) at android.app.ActivityThread.access$800(ActivityThread.java:151) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1310) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5268) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:902) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:697)

here is my code

 private class DownloadJSON extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Create a progressdialog
        mProgressDialog = new ProgressDialog(List.this);
        // Set progressdialog title
        mProgressDialog.setTitle("Android JSON Parse Tutorial");
        // Set progressdialog message
        mProgressDialog.setMessage("Loading...");
        mProgressDialog.setIndeterminate(false);
        // Show progressdialog
        mProgressDialog.show();
    }

    @Override
    protected Void doInBackground(Void... params) {
        // Create an array
        arraylist = new ArrayList<HashMap<String, String>>();
        // Retrieve JSON Objects from the given URL address
        jsonobject = JSONFunction
                .getJSONfromURL("http://localhost/atm_db/json/json.php");
        try {
            // Locate the array name in JSON
            jsonarray = jsonobject.getJSONArray("");

            for (int i = 0; i < jsonarray.length(); i++) {
                HashMap<String, String> map = new HashMap<String, String>();
                jsonobject = jsonarray.getJSONObject(i);
                // Retrive JSON Objects
                map.put("nama_atm", jsonobject.getString("nama_atm"));
                map.put("alamat", jsonobject.getString("alamat"));
                map.put("latitude", jsonobject.getString("latitude"));
                map.put("longtitude", jsonobject.getString("longtitude"));
                // Set the JSON Objects into the array
                arraylist.add(map);
            }
        } catch (JSONException e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

So I'm migrating over to Android Studios from AI2. I've got most of everything down, minus this one bit--I want to be able to send a post request to google's servers, and then to be able to parse the response in order to store part of the response in sqlite. In AI2, I used the following "blocks" to accomplish that:

This block to post,

Post Request

and this monster to store the data,

.gotText

What should these look like in java? I think after this, I'll be ready to really get down to brass tacks here.

My first post here, please go easy =)

I am developing an app on an android tablet running 4.0.4 FW which has an Ethernet port and WIFI.

I can make SIP calls over WIFI connection but when I try to register with the SIP server using Ethernet connection, it keeps timing out.

The SIP server I am using is a local server that is connected to a switch. If i plug in a WIFI access point to the server's network and connect my android to that WIFI network, calling is successful. However, when I connect the Ethernet cable from the table to the server's network. It doesn't even register with server. I keep receiving timed out response

Thanks

I want to reproduce the functionality of the UIAlertViewController as the class isn't very customisable. So here is what I did:

  1. Create a DeleteDeckViewController that only has two buttons Yes, and No, with a callback method

    class DeleteDeckViewController: UIViewController {
    
        var deleteDeck : ((deleteDeck : Bool) -> ())?
    
        @IBAction func yesButton(sender: AnyObject) {
            deleteDeck!(deleteDeck: true)
        }
    
        @IBAction func noButton(sender: AnyObject) {
            deleteDeck!(deleteDeck: false)
        }
    }
    
  2. In the main view controller when the delete button is pressed it creates a popup DeleteDeck

    func handleDelete(detailDeckView: DetailDeckView) {
    
        let deleteDeckViewController = DeleteDeckViewController(nibName: "DeleteDeckViewController", bundle: nil)
        let popup = PopupDialog(viewController: deleteDeckViewController, transitionStyle: .BounceDown, buttonAlignment: .Horizontal, gestureDismissal: true)
        presentViewController(popup, animated: true, completion: nil)
    
        deleteDeckViewController.deleteDeck(true) { () -> Void in
            print("Deck deleted")
        }
    }
    

What I want to do is to use a callback to tell my main view controller whether the user pressed yes or no and then do some actions depending on yes or no. Although, I don't know the correct way to do it. I've read a few articles on callbacks, but I don't know how to apply it in this situation. I've tried using delegates it's just that I would need to pass the DetailDeckView object around without it being used so that's why I thought callback would be a better choice.

Would someone be able to point me in the right direction?

How do you determine if a given Windows Phone running Windows Phone 10 supports USB OTG? I am aware that only a subset of phones support the protocol, but I haven't been able to find a list of which devices this includes or which specific features determine this support.

Please resolve my basic queries in regards of Windows Phone:

  1. Like Rooting in android and Jailbreak in iOS, is there anything in Windows Phone as well?

  2. Android apps are .apk. Like this, what about Windows phone apps?

  3. In case of android, some of users install apk from different sources (apart from Play Store). Can it be done in Windows phone as well?

  4. In comparison to android phone, how Windows phones are secure?

  5. Can we install .exe file in Windows Phone? and

  6. In comparison of Android, why should we consider windows phone?

Regards

GNS

I want to use a build script for a android application. So I use "apply plugin: 'com.android.application'" in my build.gradle-file. Then I can use something like:

android{ <somestuff> }

Of cause there are dependencies and repository aswell. Since here it work's like a charm. But I want to use this multiple times, so I decide to put it in a extra script and done "apply from: ''". This work's aswell. Now I was going to write a plugin to do this stuff but it did not work. I can't tell my plugin to access the android{} object. Now my question is: Is it possible to access the objects from other plugins. (myPlugin have to access the com.android.application-Plugin) OR: How can I write a plugin which just add's the values of my script in the build.gradle. I tried so many thing's but nothing worked. Hope there is a solution!

I want to make GUI-based applications for Windows, Mac, and maybe even Linux. The problem is, I don't know what programming language is best for it. I did some research, but there are many different opinions. For example, some say Java, because you can use it on multiple platforms, and some say python because it's easy. I've even considered C# and Haskell, but I don't know which one would be better. I am young, so I have time to learn more than one programming language over the years, but I want to know which one to start with.

I need to make a software that is capable of few things:

  • Open website
  • Login
  • Fill forms
  • List item
  • Find/click button
  • Close website
  • All above should be possible on ajax website i don't own, without API from website.
  • App should be standalone, possibly having basics of code-protection, so no bare javascript

Last time i did something like this i used Chrome-extensions and javascript to inject script to target website, and then used DOM manipulations and jquery to find right forms/buttons.

I could do it like this again, but it takes ages to create software, and it's not even slightly secure for me, cause anybody can see chrome extensions code.

So i wonder if there is any better way? I don't care about language,but would be great if it were client-sided.

I thought maybe use chromium to create headless browser in which i could inject javascript code - this would be more secure as i can compile all this into single file, but still without some library/technology which I do not know it will take much time.

I am having trouble with code design for current scenario of process workflow. For example by default it is set in the app that for some Request 'A' direct manager has the authority to 'approve' that but later on, this approval authority has been moved to 'department head'. How can i accommodate these changes without modifying code in future.

I am thinking on lines of creating access templates, assigning them to permission groups and adding users to those groups.

Any help on what might be problems with my propose approach or better solutions is much needed.

The user requirement might change for authorization even after deployment of system and this change needs to have minimum overhead.

This question already has an answer here:

I was wondering whether it is seen as 'good practice' or seen as acceptable for a developer to use algorithms such as binary search algorithms, quick sort algorithms, industry standard encryption/hashing algorithms etc. written by other people on the internet or in books etc.

Would this be seen as acceptable or would the programmer be seen as a 'copy-paste' coder?

In my opinion it makes sense to reuse existing algorithms as it doesn't make sense to reinvent the wheel every time I want to use one.

What is the (general) view on this topic?

Kind of as the title implies - I can understand why Apps Hungarian might crop up, but Systems Hungarian seems almost entirely pointless in a strongly-typed language. Why, then, is it so apparently prevalent in the VB world? Going back to my high school programming courses (late '00s), I had a teacher who knew nearly nothing about programming, but adhered to Systems Hungarian religiously.

I just find it odd that this naming standard persists, even in places it shouldn't (like column names in databases), and the specificity of the environments in which it does. Can anyone shed some light on this?

I am looking for best practices around the Unit of Work & Repository patterns. Our team is building a web app that for the first phase will be interacting directly with an EF backed database. For the second phase, this may be completely swapped out for a 3rd party platform that is backed by a RESTful api.

For implementation, I was thinking of just standard UnitOfWork & Repository patterns, so we only need to re-implement those interfaces for the REST api when the time comes.

Does this seem like an appropriate pattern for my scenario?

When I start a new project based on a nice starter kit like this Angular 2 one. How do you keep up with changes to a base repo like this?

I know that it is a 'starter', but it would be nice to merge smart new insights from the starter kit into my own code base. What's the most commonly used Git workflow to do this?

I mean, I add my code and change maybe a lot of files in the meantime. How do other developers handle this without spending hours solving all kinds of merge conflicts etc. Any special kinds of branching/remotes/sub repo's?

I need to include two buttons one that orders the menu alphabetically and another that leaves the normal option. I created the button and made the event but when I click the cells are not sorted, even using self.tableview.reloadData(). Do you know any way I can do this?

P.S: I am using nib / xib files

Code below:

import UIKit

class ExpandableTableViewViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
    @IBOutlet weak var tableView: UITableView!

    var selectedCellIndexPath: NSIndexPath?

    ////Heigh for cell in subTableView
    // Para pessoas que falam a língua portuguesa -> Tamanho da célula da tabela (principal e subs)
    let selectedCellHeightForSubTable: CGFloat = 40.0



    ///Heigh for cell in Main Table in (unselected)
    //Para pessoas que falam a língua portuguesa -> Tamanho da célula quando não escolhida
    let unselectedCellHeight: CGFloat = 110.0


    ////Array to save references for SubTables
    //Para pessoas que falam a língua portuguesa -> Neste array são salvas as referências para as subtabelas
    var subTables:[UITableView] = [UITableView]();


    ///fake data /// tuples type
    // Para pessoas que falam a língua portuguesa -> Aqui são instanciados os vetores que serão utilizados
    // na instanciação das células principais que serão utilizadas no armazenamento das células que irão compor
    // as tabelas e a subtabelas
    var data:([String],[[String]],[[String]],[[String]])=([String](),[[String]](),[[String]](),[[String]()]);


    override func viewDidLoad() {
        super.viewDidLoad()


        let button = UIButton(frame: CGRect(x: 25, y: 25, width: 70, height: 50))
        button.backgroundColor = .greenColor()
        button.setTitle("Ordena", forState: .Normal)
        button.addTarget(self, action: #selector(buttonAction), forControlEvents: .TouchUpInside)

        self.view.addSubview(button)

        ///Register Nib file for Main Cells
        // Para pessoas que falam a língua portuguesa -> Aqui eu faço o registro dos arquivos nib que representam
        // as células principais
        tableView.registerNib(UINib(nibName: "ExpandableCellTableViewCell",bundle: nil), forCellReuseIdentifier: "cell");


        ////Initialize array with fake data
        // Para pessoas que falam a língua portuguesa -> Aqui eu tenho a presença do método InitialiDataArray()
        // que realiza a instanciação dos vetores das células principais e secundárias.
        self.data = self.InitializeDataArray()

        self.tableView.reloadData();
    }
     func buttonAction(sender: UIButton!) {


        self.data = self.InitializeDataArraySort()
        self.tableView.reloadData()


        }

    // Para pessoas que falam a língua portuguesa -> Retorna o número de seções na TableView
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1;
    }

    // Para pessoas que falam a língua portuguesa -> Ajusta as células da TableView nas subtabelas
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        ///Main table
        if tableView == self.tableView{
            return data.0.count;
        }else{
            if let index = self.subTables.indexOf(tableView) {
                return data.1[index].count+1;///+1 for Header cell in subtableView
            }
            return 0;
        }

    }


    // Para pessoas que falam a língua portuguesa -> Ajuste das células presentes nas linhas (subtabelas)
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        if tableView == self.tableView {
            if selectedCellIndexPath == indexPath {

                ////unselected Heigh + heigh for every cell in subtable
                return unselectedCellHeight+selectedCellHeightForSubTable*CGFloat(self.data.1[indexPath.row].count+1)
            }
            return unselectedCellHeight
        }else{
            return selectedCellHeightForSubTable
        }
    }


    // Para pessoas que falam a língua portuguesa -> Processo de seleção das células e inclusão dos efeitos
    // de expandir e colapsar.
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        if tableView == self.tableView {



            if selectedCellIndexPath != nil && selectedCellIndexPath == indexPath {

                let cell = self.tableView.cellForRowAtIndexPath(indexPath) as! ExpandableCellTableViewCell;
                //let cell2 = self.tableView.cellForRowAtIndexPath(indexPath)!
                //let textoo = (cell2.viewWithTag(4) as! UILabel).text

               // print("Yuri 2")
               // print(textoo)

                cell.directionImageView.image = UIImage(named: "down");

                tableView.cellForRowAtIndexPath(indexPath)?.viewWithTag(3)!.hidden = true;
                selectedCellIndexPath = nil


            } else {
                selectedCellIndexPath = indexPath

                let cell = self.tableView.cellForRowAtIndexPath(indexPath) as! ExpandableCellTableViewCell;
                cell.directionImageView.image = UIImage(named: "up");

                tableView.cellForRowAtIndexPath(indexPath)?.viewWithTag(3)!.hidden = false;
            }




            tableView.beginUpdates()
            tableView.endUpdates()

            if selectedCellIndexPath != nil {
                // This ensures, that the cell is fully visible once expanded
                tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: .None, animated: true)

            }
        }

    }

    // Para pessoas que falam a língua portuguesa -> Efeitos de expansão e colapso quando a célula não foi 
    //selecionada
    func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
        if self.tableView.isEqual(tableView){
            let cell = self.tableView.cellForRowAtIndexPath(indexPath) as! ExpandableCellTableViewCell;
            cell.directionImageView.image = UIImage(named: "down");
            cell.viewWithTag(3)!.hidden = true;
        }

    }


    // Para pessoas que falam a língua portuguesa -> Preenchimento do conteúdo dos vetores nas células principais
    // e secundárias
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell:UITableViewCell=UITableViewCell();
        if tableView == self.tableView{
            cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
                as! ExpandableCellTableViewCell;

            (cell.viewWithTag(1) as! UILabel).text = self.data.0[indexPath.row]

            let subtable = cell.viewWithTag(3) as! UITableView;
            subtable.delegate = self;
            subtable.dataSource = self;

            subtable.registerNib(UINib(nibName: "SubTableCellTableViewCell",bundle: nil), forCellReuseIdentifier: "sub_cell");


            self.subTables.append(subtable);

            subtable.reloadData();

        }else{
            cell = tableView.dequeueReusableCellWithIdentifier("sub_cell", forIndexPath: indexPath)

            print(indexPath.row)
            print(indexPath.section)

            if indexPath.row>0{
                if let index = self.subTables.indexOf(tableView) {


                    (cell.viewWithTag(1) as! UILabel).text = self.data.1[index][indexPath.row-1]
                    (cell.viewWithTag(2) as! UILabel).text = self.data.2[index][indexPath.row-1]
                    (cell.viewWithTag(3) as! UILabel).text = self.data.3[index][indexPath.row-1]

                   // let texto = (cell.viewWithTag(1) as! UILabel).text
                   // print(texto)

                }
            }



        }

       // if("verdade".isEqualToString("verdade"))
        //{
           // print("Entrei")
        //}

        cell.selectionStyle = .None
       // let tex = (cell.viewWithTag(1) as! UILabel).text
       // print("Yuri")
       // print(tex)
        return cell;
    }



    // Para pessoas que falam a língua portuguesa -> Declaração do conteúdo das células principais e 
    // secundárias
    public func InitializeDataArray()->([String],[[String]],[[String]],[[String]]){

        var mainCells = [String]();
        var col1_SubCells = [[String]]();
        var col2_SubCells = [[String]]();
        var col3_SubCells = [[String]]();


        ////Expandable Cells Data
        mainCells.append("Genesis");
        mainCells.append("Exodus");
        mainCells.append("Leviticus");
        mainCells.append("Numbers");
        //        mainCells.append("Cell 5");

        ////First Main cell data

        ///First Col////////
        var tempArr:[String] = [String]();
        tempArr.append("Chapters")
        tempArr.append("Gen 3")
        tempArr.append("Gen 6")
        tempArr.append("Gen 9")


        col1_SubCells.append(tempArr);

        ///2nd Col
        tempArr = [String]();
        tempArr.append("")
        tempArr.append("Gen 2")
        tempArr.append("Gen 5")
        tempArr.append("Gen 8")


        col2_SubCells.append(tempArr);

        ///3rd Col
        tempArr = [String]();
        tempArr.append("")
        tempArr.append("Gen 1")
        tempArr.append("Gen 4")
        tempArr.append("Gen 7")


        col3_SubCells.append(tempArr);


        ////2nd Main cell data////////

        ///First Col
        tempArr = [String]();
        tempArr.append("Chapters")
        tempArr.append("Exo 3")
        tempArr.append("Exo 6")
        tempArr.append("Exo 9")


        col1_SubCells.append(tempArr);

        ///2nd Col
        tempArr = [String]();
        tempArr.append("")
        tempArr.append("Exo 2")
        tempArr.append("Exo 5")
        tempArr.append("Exo 8")


        col2_SubCells.append(tempArr);

        ///3rd Col
        tempArr = [String]();
        tempArr.append("")
        tempArr.append("Exo 1")
        tempArr.append("Exo 4")
        tempArr.append("Exo 7")


        col3_SubCells.append(tempArr);



        ////3rd Main cell data////////

        ///First Col
        tempArr = [String]();
        tempArr.append("Chapters")
        tempArr.append("Lev 3")
        tempArr.append("Lev 6")
        tempArr.append("Lev 9")


        col1_SubCells.append(tempArr);

        ///2nd Col
        tempArr = [String]();
        tempArr.append("")
        tempArr.append("Lev 2")
        tempArr.append("Lev 5")
        tempArr.append("Lev 8")


        col2_SubCells.append(tempArr);

        ///3rd Col
        tempArr = [String]();
        tempArr.append("")
        tempArr.append("Lev 1")
        tempArr.append("Lev 4")
        tempArr.append("Lev 7")


        col3_SubCells.append(tempArr);


        ////4th Main cell data////////

        ///First Col
        tempArr = [String]();
        tempArr.append("Chapters")
        tempArr.append("Num 3")
        tempArr.append("Num 6")
        tempArr.append("Num 9")


        col1_SubCells.append(tempArr);

        ///2nd Col
        tempArr = [String]();
        tempArr.append("")
        tempArr.append("Num 2")
        tempArr.append("Num 5")
        tempArr.append("Num 8")
        tempArr.append("Num 11")

        col2_SubCells.append(tempArr);

        ///3rd Col
        tempArr = [String]();
        tempArr.append("")
        tempArr.append("Num 1")
        tempArr.append("Num 4")
        tempArr.append("Num 7")
        tempArr.append("Num 10")

        col3_SubCells.append(tempArr);



        return (mainCells,col1_SubCells,col2_SubCells,col3_SubCells);
    }


}

how to change the initial view controller on the master detail view controller. All I want to do is have a button show the default master detail controller.

I have posted a short video completely explaining my problem. Thanks.

https://www.youtube.com/watch?v=0wFXikdcbGc

Issue

In a Messages framework app (iOS 10 beta 8), I'm able to access the activeConversation in the Messages extension using:

    guard let conversation = activeConversation else {
        print("unable to create activeConversation")
        return
    }

This works in the compact presentation style (on first load) and expanded presentation style (always).

After transitioning from compact to expanded, then to compact again, activeConversation is always nil.

(Note that activeConversation is never nil in the expanded presentation style.)

Switching View Controllers

Helper method

In MessagesViewController.swift, I'm using this code to switch out view controllers:

extension MessagesViewController {
    func switchTo(viewController controller: UIViewController) {

        // Remove existing child view controller
        for child in childViewControllers {
            child.willMove(toParentViewController: .none)
            child.view.removeFromSuperview()
            child.removeFromParentViewController()
        }

        addChildViewController(controller)

        controller.view.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(controller.view)

        NSLayoutConstraint.activate([
            controller.view.leftAnchor.constraint(equalTo: view.leftAnchor),
            controller.view.rightAnchor.constraint(equalTo: view.rightAnchor),
            controller.view.topAnchor.constraint(equalTo:
                topLayoutGuide.bottomAnchor),
            controller.view.bottomAnchor.constraint(equalTo: view.bottomAnchor)
            ])
        controller.didMove(toParentViewController: self)
    }
}

Life cycle method override

This switchTo(controller:) helper method is called in the willTransitionTo(presentationStyle:) override:

override func willTransition(to presentationStyle: MSMessagesAppPresentationStyle) {
    super.willTransition(to: presentationStyle)

    if presentationStyle == .expanded {
        guard let controller = storyboard?.instantiateViewController(withIdentifier: "expandedVC") as? ExpandedViewController
        else {
            fatalError("Unable to instantiate expandedVC")
        }
        controller.delegate = self
        switchTo(viewController: controller)
    }
    else { // .compact
        guard let controller = storyboard?.instantiateViewController(withIdentifier: "messagesViewController") as? MessagesViewController
        else {
            fatalError("Unable to instantiate an MessagesViewController")
        }
        switchTo(viewController: controller)
    }
}

Possible problems

  1. View hierarchy issue?

    I checked the view hierarchy tool in Xcode, and I haven't noticed anything that sticks out as a problem (although as it's a new tool, I might be reading it incorrectly). I also don't seem to have any memory leaks.

  2. Bug in the beta?

    Is anyone else having a problem reliably accessing the activeConversation? If so, perhaps it's just a bug in the beta.

I need to include two buttons one that orders the menu alphabetically and another that leaves the normal option. I created the button and made the event but when I click the cells are not sorted, even using self.tableview.reloadData(). Do you know any way I can do this?

P.S: I am using nib / xib files

Code below:

import UIKit

class ExpandableTableViewViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
    @IBOutlet weak var tableView: UITableView!

    var selectedCellIndexPath: NSIndexPath?

    ////Heigh for cell in subTableView
    // Para pessoas que falam a língua portuguesa -> Tamanho da célula da tabela (principal e subs)
    let selectedCellHeightForSubTable: CGFloat = 40.0



    ///Heigh for cell in Main Table in (unselected)
    //Para pessoas que falam a língua portuguesa -> Tamanho da célula quando não escolhida
    let unselectedCellHeight: CGFloat = 110.0


    ////Array to save references for SubTables
    //Para pessoas que falam a língua portuguesa -> Neste array são salvas as referências para as subtabelas
    var subTables:[UITableView] = [UITableView]();


    ///fake data /// tuples type
    // Para pessoas que falam a língua portuguesa -> Aqui são instanciados os vetores que serão utilizados
    // na instanciação das células principais que serão utilizadas no armazenamento das células que irão compor
    // as tabelas e a subtabelas
    var data:([String],[[String]],[[String]],[[String]])=([String](),[[String]](),[[String]](),[[String]()]);


    override func viewDidLoad() {
        super.viewDidLoad()


        let button = UIButton(frame: CGRect(x: 25, y: 25, width: 70, height: 50))
        button.backgroundColor = .greenColor()
        button.setTitle("Ordena", forState: .Normal)
        button.addTarget(self, action: #selector(buttonAction), forControlEvents: .TouchUpInside)

        self.view.addSubview(button)

        ///Register Nib file for Main Cells
        // Para pessoas que falam a língua portuguesa -> Aqui eu faço o registro dos arquivos nib que representam
        // as células principais
        tableView.registerNib(UINib(nibName: "ExpandableCellTableViewCell",bundle: nil), forCellReuseIdentifier: "cell");


        ////Initialize array with fake data
        // Para pessoas que falam a língua portuguesa -> Aqui eu tenho a presença do método InitialiDataArray()
        // que realiza a instanciação dos vetores das células principais e secundárias.
        self.data = self.InitializeDataArray()

        self.tableView.reloadData();
    }
     func buttonAction(sender: UIButton!) {


        self.data = self.InitializeDataArraySort()
        self.tableView.reloadData()


        }

    // Para pessoas que falam a língua portuguesa -> Retorna o número de seções na TableView
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1;
    }

    // Para pessoas que falam a língua portuguesa -> Ajusta as células da TableView nas subtabelas
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        ///Main table
        if tableView == self.tableView{
            return data.0.count;
        }else{
            if let index = self.subTables.indexOf(tableView) {
                return data.1[index].count+1;///+1 for Header cell in subtableView
            }
            return 0;
        }

    }


    // Para pessoas que falam a língua portuguesa -> Ajuste das células presentes nas linhas (subtabelas)
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        if tableView == self.tableView {
            if selectedCellIndexPath == indexPath {

                ////unselected Heigh + heigh for every cell in subtable
                return unselectedCellHeight+selectedCellHeightForSubTable*CGFloat(self.data.1[indexPath.row].count+1)
            }
            return unselectedCellHeight
        }else{
            return selectedCellHeightForSubTable
        }
    }


    // Para pessoas que falam a língua portuguesa -> Processo de seleção das células e inclusão dos efeitos
    // de expandir e colapsar.
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        if tableView == self.tableView {



            if selectedCellIndexPath != nil && selectedCellIndexPath == indexPath {

                let cell = self.tableView.cellForRowAtIndexPath(indexPath) as! ExpandableCellTableViewCell;
                //let cell2 = self.tableView.cellForRowAtIndexPath(indexPath)!
                //let textoo = (cell2.viewWithTag(4) as! UILabel).text

               // print("Yuri 2")
               // print(textoo)

                cell.directionImageView.image = UIImage(named: "down");

                tableView.cellForRowAtIndexPath(indexPath)?.viewWithTag(3)!.hidden = true;
                selectedCellIndexPath = nil


            } else {
                selectedCellIndexPath = indexPath

                let cell = self.tableView.cellForRowAtIndexPath(indexPath) as! ExpandableCellTableViewCell;
                cell.directionImageView.image = UIImage(named: "up");

                tableView.cellForRowAtIndexPath(indexPath)?.viewWithTag(3)!.hidden = false;
            }




            tableView.beginUpdates()
            tableView.endUpdates()

            if selectedCellIndexPath != nil {
                // This ensures, that the cell is fully visible once expanded
                tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: .None, animated: true)

            }
        }

    }

    // Para pessoas que falam a língua portuguesa -> Efeitos de expansão e colapso quando a célula não foi 
    //selecionada
    func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
        if self.tableView.isEqual(tableView){
            let cell = self.tableView.cellForRowAtIndexPath(indexPath) as! ExpandableCellTableViewCell;
            cell.directionImageView.image = UIImage(named: "down");
            cell.viewWithTag(3)!.hidden = true;
        }

    }


    // Para pessoas que falam a língua portuguesa -> Preenchimento do conteúdo dos vetores nas células principais
    // e secundárias
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell:UITableViewCell=UITableViewCell();
        if tableView == self.tableView{
            cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
                as! ExpandableCellTableViewCell;

            (cell.viewWithTag(1) as! UILabel).text = self.data.0[indexPath.row]

            let subtable = cell.viewWithTag(3) as! UITableView;
            subtable.delegate = self;
            subtable.dataSource = self;

            subtable.registerNib(UINib(nibName: "SubTableCellTableViewCell",bundle: nil), forCellReuseIdentifier: "sub_cell");


            self.subTables.append(subtable);

            subtable.reloadData();

        }else{
            cell = tableView.dequeueReusableCellWithIdentifier("sub_cell", forIndexPath: indexPath)

            print(indexPath.row)
            print(indexPath.section)

            if indexPath.row>0{
                if let index = self.subTables.indexOf(tableView) {


                    (cell.viewWithTag(1) as! UILabel).text = self.data.1[index][indexPath.row-1]
                    (cell.viewWithTag(2) as! UILabel).text = self.data.2[index][indexPath.row-1]
                    (cell.viewWithTag(3) as! UILabel).text = self.data.3[index][indexPath.row-1]

                   // let texto = (cell.viewWithTag(1) as! UILabel).text
                   // print(texto)

                }
            }



        }

       // if("verdade".isEqualToString("verdade"))
        //{
           // print("Entrei")
        //}

        cell.selectionStyle = .None
       // let tex = (cell.viewWithTag(1) as! UILabel).text
       // print("Yuri")
       // print(tex)
        return cell;
    }



    // Para pessoas que falam a língua portuguesa -> Declaração do conteúdo das células principais e 
    // secundárias
    public func InitializeDataArray()->([String],[[String]],[[String]],[[String]]){

        var mainCells = [String]();
        var col1_SubCells = [[String]]();
        var col2_SubCells = [[String]]();
        var col3_SubCells = [[String]]();


        ////Expandable Cells Data
        mainCells.append("Genesis");
        mainCells.append("Exodus");
        mainCells.append("Leviticus");
        mainCells.append("Numbers");
        //        mainCells.append("Cell 5");

        ////First Main cell data

        ///First Col////////
        var tempArr:[String] = [String]();
        tempArr.append("Chapters")
        tempArr.append("Gen 3")
        tempArr.append("Gen 6")
        tempArr.append("Gen 9")


        col1_SubCells.append(tempArr);

        ///2nd Col
        tempArr = [String]();
        tempArr.append("")
        tempArr.append("Gen 2")
        tempArr.append("Gen 5")
        tempArr.append("Gen 8")


        col2_SubCells.append(tempArr);

        ///3rd Col
        tempArr = [String]();
        tempArr.append("")
        tempArr.append("Gen 1")
        tempArr.append("Gen 4")
        tempArr.append("Gen 7")


        col3_SubCells.append(tempArr);


        ////2nd Main cell data////////

        ///First Col
        tempArr = [String]();
        tempArr.append("Chapters")
        tempArr.append("Exo 3")
        tempArr.append("Exo 6")
        tempArr.append("Exo 9")


        col1_SubCells.append(tempArr);

        ///2nd Col
        tempArr = [String]();
        tempArr.append("")
        tempArr.append("Exo 2")
        tempArr.append("Exo 5")
        tempArr.append("Exo 8")


        col2_SubCells.append(tempArr);

        ///3rd Col
        tempArr = [String]();
        tempArr.append("")
        tempArr.append("Exo 1")
        tempArr.append("Exo 4")
        tempArr.append("Exo 7")


        col3_SubCells.append(tempArr);



        ////3rd Main cell data////////

        ///First Col
        tempArr = [String]();
        tempArr.append("Chapters")
        tempArr.append("Lev 3")
        tempArr.append("Lev 6")
        tempArr.append("Lev 9")


        col1_SubCells.append(tempArr);

        ///2nd Col
        tempArr = [String]();
        tempArr.append("")
        tempArr.append("Lev 2")
        tempArr.append("Lev 5")
        tempArr.append("Lev 8")


        col2_SubCells.append(tempArr);

        ///3rd Col
        tempArr = [String]();
        tempArr.append("")
        tempArr.append("Lev 1")
        tempArr.append("Lev 4")
        tempArr.append("Lev 7")


        col3_SubCells.append(tempArr);


        ////4th Main cell data////////

        ///First Col
        tempArr = [String]();
        tempArr.append("Chapters")
        tempArr.append("Num 3")
        tempArr.append("Num 6")
        tempArr.append("Num 9")


        col1_SubCells.append(tempArr);

        ///2nd Col
        tempArr = [String]();
        tempArr.append("")
        tempArr.append("Num 2")
        tempArr.append("Num 5")
        tempArr.append("Num 8")
        tempArr.append("Num 11")

        col2_SubCells.append(tempArr);

        ///3rd Col
        tempArr = [String]();
        tempArr.append("")
        tempArr.append("Num 1")
        tempArr.append("Num 4")
        tempArr.append("Num 7")
        tempArr.append("Num 10")

        col3_SubCells.append(tempArr);



        return (mainCells,col1_SubCells,col2_SubCells,col3_SubCells);
    }


}

I recently deployed an app update with CloudKit support. It has been working fine, and all of sudden I'm starting to get this error:

Internal Error" (4000); "Couldn't get a signing certificate"

And my app can't fetch the information from CloudKit.

My provisioning profiles are ok. I changed Apple IDs to check, and none works. I changed iPhone, and still no luck.

Development environment does work on simulator, but not on iPhone. Obviously production environment can't be fetch from simulator.

The most interesting part is that if I connect my iPhone to Mac, and go to Xcode -> Devices, open my app downloaded from App Store, and read the devices logs, when I attempt to fetch the records, it logs:

Sep 5 15:26:23 Rogers-6 cloudd[7493] <Error>: We didn't get a Mescal cert back from the server Sep 5 15:26:23 Rogers-6 cloudd[7493] <Error>: Couldn't renew Mescal session. Failing this request: <CKError 0x12eee3680: "Internal Error" (4000); "Couldn't get a signing certificate">

I searched for that Mescal error in Google with between quotation marks and got zero results.

There's only one Stack Overflow question regarding this issue:

  1. CloudKit: "Internal Error" (1/4000); "Couldn't get a signing certificate"> And it doesn't help.

Last, but most important, it is working for some users afaik. A friend of mine has my app installed, and it fetches the data with no problems at all.

Any clues?

Thanks in advance.

I want the users' location to be updated in cloudkit but my code just save a new record every time. How can the existing record be modified or replaced by the new one?

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
    {
        let location = locations.last
        let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude)
        let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
        self.mapView.setRegion(region, animated: true)
        self.locationManager.stopUpdatingLocation()
        locationRecord.setObject(location, forKey: "location")
        let publicData = CKContainer.defaultContainer().publicCloudDatabase
        publicData.saveRecord(locationRecord) { record, error in
        }
            if error == nil
            {
                print("Location saved")
                self.loc1 = location!
            }
    }