I'm trying to retrieve data from a simple MySQL database that is managed locally with MAMP on my Macbook Pro.
When I run the project in Xcode's simulator, it work perfectly. The data is retrieved from the database when a button is pushed. It works in the Google Chrome browser also when you run the code in Netbeans.
When I run the code on the device via Xcode, the app looks like it should and navigates like it should, but the button does not retrieve the data when pushed.
Do I have to connect via my ip address in order for it to work on the device? Can anyone explain an easy way to do this? Please.
Below is the code for retrieving the data;
$(document).on('click', '#studentButton',function() {
$.getJSON('http://localhost:8888/htdocs/php/json-data-students.php', function(data) {
$.each(data.students, function(index, student) {
$('#Row1').append('<p> ID: ' + student.studentID+ '</p>');
$('#Row2').append('<p> < '+ student.firstName +' > ')+ '</p>';
$('#Row3').append('<p> < '+ student.lastName +' > ')+ '</p>';
$('#Row4').append('<p> Course ID: ' + student.courseID+ '</p');
});
});
});
localhost
is the IP address 127.0.0.1 which represents the host that the app is running on.
When you run your app in the simulator (on the Mac), then localhost
happens to be same host that is also running your database. So your app is able to connect just fine.
When you run your app on a real iOS device, then localhost
(as seen by the iOS app) is the iOS device and not the host running your database. So our app fails to connect since the database isn't running on the iOS device.
So you need to replace localhost
with the local IP address of your Mac. Most likely it will be something like 192.168.1.x
where x
will be 1
or some other number between 1
and 255
.
Once you make that change your app will work from a real device or the simulator. Of course your Mac's IP address can change over time. But this is just for testing any way. You certainly won't be running your database on your Mac when you publish your app to the App Store.