tag:blogger.com,1999:blog-2591762378811022962024-03-19T02:49:06.195-07:00Pronoid AndroidJonhttp://www.blogger.com/profile/17475458068193351080noreply@blogger.comBlogger39125tag:blogger.com,1999:blog-259176237881102296.post-65790784055296953072011-09-21T20:27:00.000-07:002011-09-22T12:33:57.994-07:00Image sizing and scraping with JQuery and Rails<div dir="ltr" style="text-align: left;" trbidi="on">
<br />
I know, I know, long time no type. Not my fault, I swear! First I went <a href="http://www.flickr.com/photos/rezendi/sets/72157627126826525/">travelling</a>, then I had a buncha work to do, then I went to San Francisco <a href="http://techcrunch.com/2011/09/17/disruptive-tendencies/">TechCrunch Disrupt</a>, all of which occupied my time. Well, I suppose, on reflection, all those things <i>were</i> my fault, but, um ... look, I'm back now, OK?<br />
<br />
Back with a li'l discussion of image sizing and scraping with Rails and JQuery, for a project I can't really talk about yet. Suffice to say that sometimes I want to calculate the size of various remote images - quite a lot of them, in fact, making performance important - and sometimes I want to scrape all the images from a set of web pages.<br />
<br />
I thought the first task was going to be tricky. And maybe it is. But fortunately, someone has solved it for me, via the totally awesome <a href="https://github.com/sdsykes/fastimage">FastImage</a> Ruby gem, for which praise should be heaped upon one sdsykes. It works exactly like advertised, which is to say, like this:<br />
<br />
<br />
<pre> def self.picture_info_for(url)
return nil if url.blank?
begin
size = FastImage.size(url)
return size #[width, height]
rescue
logger.info "Error getting info for picture at "+url.to_s
return Array[0,0] #this makes sense for my app, but maybe not yours
end
end
</pre>
<br />
<br />
<div dir="ltr" style="text-align: left;" trbidi="on">
So, hurrah! This meant the scraping bit was actually tricker. Sure, I could have done it all in Rails, but it's user-facing, and I didn't want the user to have to wait for a bunch of potentially sequential http requests to complete without seeing any results. I could have done it all on the client side, but parsing HTML with Javascript, even with JQuery, sounded painful and fraught with difficulties, compared to using the dead-easy Hpricot gem. So I came up with a compromise I quite like:<br />
<br />
1. On the client side: (written using <a href="http://haml-lang.com/">HAML</a>, which I mostly adore)</div>
<pre>- @image_urls.each_with_index do |url,idx|
= link_to url, url
%div{:id => 'page_'+idx.to_s}
%script
$(function() {
- @image_urls.each_with_index do |url,idx|
$.ajax({
url: '/stories/scrape_images?url=#{CGI::escape(url)}',
success: function(msg){ $('#page_#{idx}').html(msg); },
error: function(msg){ $('#page_#idx}').html(msg); }
});
});
</pre>
<div dir="ltr" style="text-align: left;" trbidi="on">
<br />
2. On the server, to first create and then respond to that client page:</div>
<pre> def popup_scraped_images
start_time = Time.now
@image_urls = []
@seed = Seed.find(params[:seed_id])
@seed.active_signals.each do |signal|
next if signal.main_url.blank?
@image_urls << signal.main_url
end
end
def scrape_images
url = params[:url]
slash = url =~ /[^\/]\/[^\/]/
host = slash.nil? ? "" : url[0,slash+1]
html = ''
page = HTTParty.get(url, :timeout => 5)
Hpricot(page).search("//img").each do |element|
img_src = element.attributes["src"]
img_src = host+img_src if img_src.match(/^\//)
html += '<img src="'+img_src+'" />' if img_src.match(/^http/)
end</pre>
<pre> end<pre></pre>
</pre>
<div dir="ltr" style="text-align: left;" trbidi="on">
<br />
Hopefully how they all interact is self-explanatory. Et voila - semi-asynchronous Rails/JQuery image scraping, handled on the server side for easy caching if need be later on.
</div>
</div>
Jonhttp://www.blogger.com/profile/17475458068193351080noreply@blogger.com262tag:blogger.com,1999:blog-259176237881102296.post-30605062890471673782011-05-16T08:44:00.000-07:002011-05-16T08:53:35.825-07:00Looting Android's log filesHello, my faithful <strike>droogs</strike>readers. Been awhile since I've posted here, because I've been super-busy, mostly writing code. But I'm off travelling for a couple of months shortly (Ethiopia, France, Ladakh) so I thought I'd leave you with a little Android/Bluetooth tidbit before I go:<br /><br />In theory, any Android 2.1-or-later device can open serial port protocols to any Bluetooth device. In practice, though, a bunch of handset manufacturers have, for reasons known to them alone, <a href="http://stackoverflow.com/questions/4215398/bluetooth-device-not-discoverable">crippled their Bluetooth stack</a> so that they can't Discover (a word with a loaded meaning in Bluetooth) any device with a generic (ie set to 0) Bluetooth class.<br /><br />How annoying, no? However, it turns out that - even on those devices - you <i>can</i> pair with and connect to those devices, if you know their address. "But Jon," you say, "how can I <i>get</i> their address, if the Discovery process has been crippled?"<br /><br />Well. It turns out that the Qualcomm drivers in question, when they ignore the generic Bluetooth devices, <i>do</i> write to the Android log file the fact that they are ignoring it. So all you need to do is mine your log files for the address. How do you do that? So glad you asked.<br /><br />First, add to your AndroidManifest:<br /><PRE><br /> <uses-permission android:name="android.permission.READ_LOGS" /><br /></PRE><br /><br />Second, use this method:<br /><PRE><br /> private Set<BluetoothDevice> checkLogs() {<br /> HashSet<BluetoothDevice> devices = new HashSet<BluetoothDevice>();<br /> if (mAdapter==null)<br /> return devices;<br /><br /> //check the logs<br /> Log.i(""+this, "Log check...");<br /> try {<br /> Process process = Runtime.getRuntime().exec("logcat -d *:e");<br /> BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));<br /> String line;<br /> String deviceAddress=null;<br /> while ((line = bufferedReader.readLine()) != null) {<br /> if (line.indexOf("0x00 - skip it") > 0) {<br /> int end = line.indexOf("] class");<br /> int start = line.indexOf("Device [");<br /> if (start>=0)<br /> start=start+"Device [".length();<br /> deviceAddress = line.substring(start, end);<br /> Log.i(""+this, "Found "+deviceAddress+" in log");<br /> BluetoothDevice device = mAdapter.getRemoteDevice(deviceAddress) ;<br /> devices.add(device);<br /> //String deviceName = device.getName()==null ? device.getAddress() : device.getName();<br /> //Util.DoToast(Main.this, "Discovered device "+deviceName);<br /> }<br /> }<br /> bufferedReader.close();<br /> process.destroy();<br /> return devices;<br /> }<br /> catch(IOException ex) {<br /> Log.e(""+this, "Error checking logs - "+ex);<br /> ex.printStackTrace();<br /> return null;<br /> }<br /> }<br /></PRE><br /><br />...and finally, just connect to the device explicitly:<br /><br /><PRE><br /> btSocket = device.createRfcommSocketToServiceRecord(GatewayManagerConversation.uuid);<br /> btSocket.connect();<br /></PRE><br /><br />...and that should trigger the pairing process, and after pairing, you can connect to the device (which will be in your local cache of paired devices, as normal.)<br /><br />Hope that helps!Jonhttp://www.blogger.com/profile/17475458068193351080noreply@blogger.com43tag:blogger.com,1999:blog-259176237881102296.post-78739184893408530272011-01-03T17:31:00.000-08:002011-01-03T17:52:38.155-08:00Two great maps that taste great togetherI spent yesterday adding <a href="http://code.google.com/p/osmdroid/">OSMDroid</a> support to <a href="http://itravelfree.net/">iTravelFree</a>; here's a little precis of what I learned about letting users swap back and forth between Google Maps and OpenStreetMaps within the same Android Activity.<br /><br /><i>Why?</i> you might ask: well, two reasons. One, OpenStreetMaps is a pretty cool project. Two, OSMDroid lets you access OpenStreetMaps <i>even while offline</i>, which is pretty awesome for a travel app, and while Google Maps App 5.0 has some offline support, it not you decides which tiles get cached. Mind you, creating and downloading OSM maps to Android is non-trivial, though the next <b>iTravelFree</b> release will make it much easier.<br /><br />Also, it's just kinda interesting swapping back and forth between GMaps and OSM and seeing the differences between the two.<br /><br />Anyway: how to do it? With a basic Decorator pattern, ie we roll our own MapView object (in my case, ITRMapView) which wraps both a Google MapView and and OpenStreetMapView, and forwards method calls appropriately depending on its state.<br /><br />Arguably the best implementation would be via a common ITRMapViewImplementation interface and a concrete class for every map type. (If there were more than two map types, this would no longer really be arguable.) But I implemented it quick-and-dirty, with a bunch of if statements, which does at least have the serendipitous effect of being easy to use as an example.<br /><br />Anyhoo, without further ado, here's the code:<br /><PRE><br />/**<br /> * Wrapper class which lets a MapActivity switch back and forth between Google Maps and OpenStreetMaps.<br /> */<br />public class ITRMapView {<br /> private MapActivity mapActivity;<br /> private BalloonLayout balloon;<br /><br /> private ITRGMapView gmap;<br /> public ITRGMapView getGMap()<br /> {<br /> if (gmap==null) {<br /> gmap = new ITRGMapView(mapActivity, "my_api_key");<br /> gmap.setClickable(true);<br /> gmap.setMapActivity(mapActivity);<br /> gmap.setBuiltInZoomControls(true);<br /> gmapLocation = new com.google.android.maps.MyLocationOverlay(mapActivity, gmap);<br /> balloon = BalloonLayout.GetBalloonFor(mapActivity);<br /> }<br /> return gmap;<br /> }<br /> private com.google.android.maps.MyLocationOverlay gmapLocation;<br /> private ListingsOverlay gmapListingsOverlay;<br /><br /> private OpenStreetMapView osm;<br /> public OpenStreetMapView getOSMMap() { return osm; }<br /> private org.andnav.osm.views.overlay.MyLocationOverlay osmLocation;<br /> private OpenStreetMapViewItemizedOverlay<OpenStreetMapViewOverlayItem> osmListingsOverlay;<br /><br /> private boolean osmActive=false;<br /> public boolean isOSMActive() { return osmActive; }<br /> public void setOSMActive(boolean doOSM) { osmActive=doOSM; }<br /><br /> public ITRMapView(MapActivity activity) {<br /> mapActivity=activity;<br /> }<br /><br /> public void setOSMMap(OpenStreetMapView theOSMMap) {<br /> osm=theOSMMap;<br /> osmLocation = new org.andnav.osm.views.overlay.MyLocationOverlay(mapActivity, osm);<br /> int centerLat = gmap==null ? 0 : gmap.getMapCenter().getLatitudeE6();<br /> int centerLon = gmap==null ? 0 : gmap.getMapCenter().getLongitudeE6();<br /> int zoom = gmap==null ? 10 : gmap.getZoomLevel();<br /> org.andnav.osm.util.GeoPoint center = new org.andnav.osm.util.GeoPoint(centerLat, centerLon);<br /> osm.getController().setCenter(center);<br /> osm.getController().setZoom(zoom);<br /> osm.setUpFor(mapActivity);<br /> }<br /><br /> public void onResume() {<br /> if (gmapLocation!=null) {<br /> gmapLocation.enableMyLocation();<br /> gmapLocation.enableCompass();<br /> }<br /> if (osmLocation!=null) {<br /> osmLocation.enableMyLocation();<br /> osmLocation.enableCompass();<br /> }<br /> }<br /> public void onPause() {<br /> if (gmapLocation!=null) {<br /> gmapLocation.disableMyLocation();<br /> gmapLocation.disableCompass();<br /> }<br /> if (osmLocation!=null) {<br /> osmLocation.disableMyLocation();<br /> osmLocation.disableCompass();<br /> }<br /> }<br /><br /> public void centerAndZoom(int centerLat, int centerLon, int spanLat, int spanLon) {<br /> Log.i(""+this, "Center and zoom: "+centerLat+" "+centerLon+" "+spanLat+" "+spanLon+" osm "+osmActive);<br /> if (osmActive) {<br /> org.andnav.osm.util.GeoPoint center = new org.andnav.osm.util.GeoPoint(centerLat, centerLon);<br /> OpenStreetMapViewController controller = osm.getController();<br /> controller.setCenter(center);<br /><br /> //quick-and-dirty, because zoomToSpan doesn't work<br /> Integer maxSpan = Math.max(spanLat, spanLon);<br /> Double ln = Math.log(maxSpan.doubleValue());<br /> Integer zoomLevel = 20-ln.intValue();<br /> if (zoomLevel>5)<br /> zoomLevel+=2;<br /> if (zoomLevel>18)<br /> zoomLevel=18;<br /> controller.setZoom(zoomLevel);<br /> }<br /> else {<br /> com.google.android.maps.GeoPoint center = new com.google.android.maps.GeoPoint(centerLat, centerLon);<br /> MapController controller = gmap.getController();<br /> controller.setCenter(center);<br /> controller.zoomToSpan(spanLat, spanLon); <br /> }<br /> }<br /> <br /> public int getMapCenterLatE6() {<br /> if (osmActive) {<br /> int lat = osm.getMapCenterLatitudeE6();<br /> //Need to clamp to be consistent with GMaps<br /> if (lat<-180000000)<br /> lat+=360000000;<br /> if (lat>180000000)<br /> lat-=360000000;<br /> return lat;<br /> }<br /> return gmap.getMapCenter().getLatitudeE6();<br /> }<br /> public int getMapCenterLonE6() {<br /> if (osmActive) {<br /> int lon = osm.getMapCenterLongitudeE6();<br /> //Need to clamp to be consistent with GMaps<br /> if (lon<-180000000)<br /> lon+=360000000;<br /> if (lon>180000000)<br /> lon-=360000000;<br /> return lon;<br /> }<br /> return gmap.getMapCenter().getLongitudeE6();<br /> }<br /><br /> public void fillMap(ProgressIndicator indicator, HashSet<MappableItem> mCurrentSubset) {<br /> if (osmActive)<br /> fillOSMMap(indicator, mCurrentSubset);<br /> else<br /> fillGMap(indicator, mCurrentSubset);<br /> }<br /> synchronized void fillOSMMap(ProgressIndicator indicator, HashSet<MappableItem> mCurrentSubset) {<br /> if (mCurrentSubset==null)<br /> return;<br /><br /> ArrayList<OpenStreetMapViewOverlayItem> items = new ArrayList<OpenStreetMapViewOverlayItem>();<br /> MappableItem[] toMap = mCurrentSubset.toArray(new MappableItem[mCurrentSubset.size()]);<br /> int listEnd=Math.min(toMap.length, Settings.GetMapMax());<br /> for (int i=0; i<listEnd; i++) {<br /> OpenStreetMapViewOverlayItem newItem = new OpenStreetMapViewOverlayItem(<br /> toMap[i].getIDString(),<br /> toMap[i].getMapDetailText(),<br /> new GeoPoint(toMap[i].getLatitudeE6(), toMap[i].getLongitudeE6()));<br /> newItem.setMarker(toMap[i].getMarker(mapActivity));<br /> items.add(newItem);<br /> if (indicator!=null)<br /> indicator.showProgress(i, listEnd);<br /> }<br /><br /> osmListingsOverlay = new OpenStreetMapViewItemizedOverlay<OpenStreetMapViewOverlayItem>(<br /> mapActivity,items,<br /> new OpenStreetMapViewItemizedOverlay.OnItemGestureListener<OpenStreetMapViewOverlayItem>(){<br /> @Override<br /> public boolean onItemSingleTapUp(int index, OpenStreetMapViewOverlayItem item) {<br /> RelativeLayout rl = (RelativeLayout) osm.getParent();<br /> rl.removeView(balloon);<br /> balloon.disablePointer();<br /> balloon.setUpTapFor(mapActivity, item.getTitle(), item.getSnippet());<br /> RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(200, 100); <br /> params.addRule(RelativeLayout.ALIGN_PARENT_TOP);<br /> params.addRule(RelativeLayout.CENTER_HORIZONTAL);<br /> rl.addView(balloon, params);<br /> return true;<br /> }<br /><br /> @Override<br /> public boolean onItemLongPress(int index, OpenStreetMapViewOverlayItem item) {<br />// Toast.makeText(mapActivity, "Item '" + item.mTitle + "' (index=" + index + ") got long pressed", Toast.LENGTH_LONG).show();<br /> return false;<br /> }<br /> });<br /> }<br /> synchronized void fillGMap(ProgressIndicator indicator, HashSet<MappableItem> mCurrentSubset) {<br /> if (mCurrentSubset==null)<br /> return;<br /><br /> Drawable defaultMarker = mapActivity.getResources().getDrawable(R.drawable.map_fave);<br /> gmapListingsOverlay = new ListingsOverlay(mapActivity, gmap, defaultMarker);<br /> MappableItem[] toMap = mCurrentSubset.toArray(new MappableItem[mCurrentSubset.size()]);<br /> int listEnd=Math.min(toMap.length, Settings.GetMapMax());<br /> for (int i=0; i<listEnd; i++) {<br /> Drawable marker = toMap[i].getMarker(mapActivity);<br /> ListingOverlayItem overlay = toMap[i].getListingOverlayItem();<br /> if (overlay!=null)<br /> gmapListingsOverlay.addItem(overlay, marker);<br /> if (indicator!=null)<br /> indicator.showProgress(i, listEnd);<br /> }<br /> gmapListingsOverlay.doPopulate();<br /> }<br /><br /> public void showListingsOverlay() {<br /> if (osmActive) {<br /> List<OpenStreetMapViewOverlay> mapOverlays = osm.getOverlays();<br /> if (!mapOverlays.contains(osmListingsOverlay))<br /> mapOverlays.add(osmListingsOverlay);<br /> if (!mapOverlays.contains(osmLocation))<br /> mapOverlays.add(osmLocation);<br /> }<br /> else {<br /> List<Overlay> mapOverlays = gmap.getOverlays();<br /> if (!mapOverlays.contains(gmapListingsOverlay))<br /> mapOverlays.add(gmapListingsOverlay);<br /> if (!mapOverlays.contains(gmapLocation))<br /> mapOverlays.add(gmapLocation);<br /> }<br /> postInvalidate();<br /> }<br /><br /> public void postInvalidate() {<br /> if (osmActive)<br /> osm.postInvalidate();<br /> else<br /> gmap.postInvalidate();<br /> }<br /> <br /> public int getLatitudeSpan() {<br /> if (osmActive)<br /> return osm.getLatitudeSpanE6();<br /> return gmap.getLatitudeSpan();<br /> }<br /> public int getLongitudeSpan() {<br /> if (osmActive)<br /> return osm.getLongitudeSpanE6();<br /> return gmap.getLongitudeSpan();<br /> }<br /> public int getZoomLevel() {<br /> if (osmActive)<br /> return osm.getZoomLevel();<br /> return gmap.getZoomLevel();<br /> }<br /><br />}<br /></PRE><br /><br />And how is it used? Well, the MapActivity includes code like this:<br /><PRE><br /> private void switchMapMode() {<br /> int lastLat = mapView.getMapCenterLatE6();<br /> int lastLon = mapView.getMapCenterLonE6();<br /> int lastLatSpan = mapView.getLatitudeSpan();<br /> int lastLonSpan = mapView.getLatitudeSpan();<br /> boolean willHandleCenterZoom = lastLat!=0 && lastLon!=0 && lastLatSpan!=0 && lastLonSpan!=0;<br /><br /> if (mapView.isOSMActive())<br /> useGMap(!willHandleCenterZoom);<br /> else<br /> useOSMMap(!willHandleCenterZoom);<br /><br /> if (willHandleCenterZoom)<br /> mapView.centerAndZoom(lastLat, lastLon, lastLatSpan, lastLonSpan);<br /> }<br /> private void useGMap(boolean doCenterZoom) {<br /> mapView.setOSMActive(false);<br /> setContentView(R.layout.map);<br /> //remove map view from old parent, if any<br /> ITRGMapView gmap = mapView.getGMap();<br /> RelativeLayout rl = (RelativeLayout) gmap.getParent();<br /> if (rl!=null)<br /> rl.removeView(gmap);<br /> //add map view to new parent<br /> rl = (RelativeLayout) findViewById(R.id.mapLayout);<br /> rl.addView(mapView.getGMap());<br /> setUpMap(doCenterZoom);<br /> }<br /> private void useOSMMap(boolean doCenterZoom) {<br /> mapView.setOSMActive(true);<br /> setContentView(R.layout.map_osm);<br /> mapView.setOSMMap((ITROSMMapView)findViewById(R.id.mapview_osm));<br /> setUpMap(doCenterZoom);<br /> new FillMapTask().execute();<br /> }<br /> private void setUpMap(boolean doCenterZoom) {<br /> registerForContextMenu(findViewById(R.id.tagButton));<br /> registerForContextMenu(findViewById(R.id.mapButton));<br /> setUpToolbar();<br /> if (doCenterZoom && mCurrentLat!=0 && mCurrentLong!=0 && mCurrentLatSpan!=0 && mCurrentLongSpan!=0)<br /> mapView.centerAndZoom(mCurrentLat, mCurrentLong, mCurrentLatSpan, mCurrentLongSpan);<br /> else if (doCenterZoom && mapView.isOSMActive() && mCurrentLat==0 && mCurrentLong==0)<br /> mapView.centerAndZoom(51000000, 0, 1000000, 1000000);<br /> }<br /></PRE><br /><br />Of some interest, I suppose, are the BalloonLayout and ListingsOverlay classes mentioned above, so:<br /><br /><PRE><br />public class BalloonLayout extends LinearLayout {<br /> private boolean pointerEnabled=true;<br /> public void disablePointer() { pointerEnabled=false; }<br /> public void enablePointer() {pointerEnabled=true; }<br /><br /> public BalloonLayout(Context context) {<br /> super(context);<br /> }<br /><br /> public BalloonLayout(Context context, AttributeSet set) {<br /> super(context, set);<br /> }<br /><br /> @Override<br /> protected void dispatchDraw(Canvas canvas) {<br /> <br /> Paint panelPaint = new Paint();<br /> panelPaint.setARGB(0, 0, 0, 0);<br /> RectF baloonRect = new RectF();<br /> baloonRect.set(0,0, getMeasuredWidth(), 2*(getMeasuredHeight()/3));<br /> panelPaint.setARGB(230, 255, 255, 255); <br /> canvas.drawRoundRect(baloonRect, 10, 10, panelPaint);<br /><br /> if (pointerEnabled) {<br /> Path baloonTip = new Path();<br /> baloonTip.moveTo(5*(getMeasuredWidth()/8), 2*(getMeasuredHeight()/3));<br /> baloonTip.lineTo(getMeasuredWidth()/2, getMeasuredHeight());<br /> baloonTip.lineTo(3*(getMeasuredWidth()/4), 2*(getMeasuredHeight()/3));<br /> canvas.drawPath(baloonTip, panelPaint);<br /> }<br /> <br /> super.dispatchDraw(canvas);<br /> }<br /> <br /> public void setUpTapFor(final Activity activity, String title, String snippet)<br /> {<br /> setVisibility(View.VISIBLE);<br /> TextView titleText = (TextView) findViewById(R.id.detailText);<br /> titleText.setText(snippet);<br /><br /> ImageButton detailButton = (ImageButton) findViewById(R.id.detailGo);<br /> try {<br /> final Long id = Long.valueOf(title);<br /> detailButton.setOnClickListener(new View.OnClickListener() {<br /> public void onClick(View view) {<br /> Intent intent = new Intent(activity, ListingActivity.class);<br /> intent.putExtra(ListingActivity.KEY_ID, id);<br /> activity.startActivityForResult(intent, 0);<br /> //not pretty!<br /> if (activity instanceof ITRMapActivity)<br /> ((ITRMapActivity)activity).editedListingID=id;<br /> }<br /> });<br /> }<br /> catch (NumberFormatException ex) {<br /> ex.printStackTrace();<br /> }<br /><br /> public static BalloonLayout GetBalloonFor(Activity activity) {<br /> LayoutInflater layoutInflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);<br /> final BalloonLayout balloon = (BalloonLayout) layoutInflater.inflate(R.layout.map_balloon, null);<br /> RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(200,100);<br /> layoutParams.addRule(RelativeLayout.CENTER_VERTICAL);<br /> layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL);<br /> balloon.setLayoutParams(layoutParams); <br /> <br /> ImageButton closeButton = (ImageButton) balloon.findViewById(R.id.detailClose);<br /> closeButton.setOnClickListener(new View.OnClickListener() {<br /> public void onClick(View view) {<br /> balloon.setVisibility(View.GONE);<br /> }<br /> });<br /> return balloon;<br /> }<br />}<br /></PRE><br /><br />although I have to work the kinks out of placing the balloon on the OSM map still. As for the ListingsOverlay,<br /><br /><PRE><br />public class ListingsOverlay extends ItemizedOverlay<ListingOverlayItem> {<br /> private MapActivity activity;<br /> private ITRGMapView mapView;<br /> private BalloonLayout balloon;<br /> private ArrayList<ListingOverlayItem> items=new ArrayList<ListingOverlayItem>();<br /> public ArrayList<ListingOverlayItem> getItems() { return items; }<br /><br /> public ListingsOverlay(MapActivity anActivity, ITRGMapView aMapView, android.graphics.drawable.Drawable defaultMarker) {<br /> super(defaultMarker);<br /> activity=anActivity;<br /> mapView=aMapView;<br /> balloon = BalloonLayout.GetBalloonFor(activity);<br /> }<br /><br /> public void addItem(ListingOverlayItem item, Drawable marker) {<br /> if (item!=null && marker!=null && !items.contains(item)) {<br /> super.boundCenterBottom(marker);<br /> item.setMarker(marker);<br /> items.add(item);<br /> }<br /> }<br /><br /> public void doPopulate() {<br /> populate();<br /> setLastFocusedIndex(-1);<br /> }<br /><br /> @Override<br /> protected ListingOverlayItem createItem(int i) {<br /> return(items.get(i));<br /> }<br /><br /> @Override<br /> public int size() {<br /> return(items.size());<br /> }<br /><br /> @Override<br /> protected boolean onTap(int i) {<br /> mapView.removeView(balloon);<br /> balloon.enablePointer();<br /> ListingOverlayItem item = items.get(i);<br /> balloon.setUpTapFor(activity, item.getTitle(), item.getSnippet());<br /> MapView.LayoutParams params = new MapView.LayoutParams(200, 100, item.getPoint(), MapView.LayoutParams.BOTTOM_CENTER); <br /> mapView.addView(balloon, params);<br /> return true;<br /> }<br /><br />}<br /><br /></PRE><br /><br />I hereby BSD 2.0-release all the above code, if anyone wants to use it - enjoy!Jonhttp://www.blogger.com/profile/17475458068193351080noreply@blogger.com31tag:blogger.com,1999:blog-259176237881102296.post-37146186854963134492010-11-20T07:18:00.001-08:002010-11-20T07:23:58.215-08:00HttpHelper for all, reduxYeah, I know I said I wouldn't be posting much, but I've cleaned up and updated my HttpHelper class for one of my paid projects so that it supports cookies, form/multipart file uploads, non-ASCII characters, etc., so I thought I'd release it into the wild for <a href="http://pa.rezendi.com/2010/06/httphelper-for-all.html">y'all</a>.<br /><br /><a href="http://en.wikipedia.org/wiki/Apache_License">Apache License 2.0</a>, as before.<br /><br />The interface should be pretty self-evident from the .h file:<br /><br /><PRE><br />//<br />// HttpHelper.h<br />//<br />// Created by Jon Evans on 04/09/09.<br />// Copyright 2009 Jon Evans. Apache 2.0 license.<br />//<br /><br />#import <Foundation/Foundation.h><br /><br />@interface HttpHelper : NSObject {<br />}<br /><br />//Convenience methods<br />+(NSURLRequestCachePolicy)getCachePolicyFor:(NSString *)urlString;<br /><br />//Cookie handling<br />+(void) useCookies:(BOOL)use;<br />+(NSArray*) latestCookies;<br />+(void) getCookiesFrom:(NSHTTPURLResponse*)response forURL:(NSURL*)url;<br /><br />//HTTP Posts<br />+(NSURLRequest*) buildPostRequestForURL:(NSString *)urlString withData:(NSDictionary*) data;<br />+(NSURLRequest *) buildRequestWithPostKeys:(NSArray *) postKeys postValues:(NSArray *) postValues urlString:(NSString *)urlString;<br />+(BOOL) doPost:(NSURLRequest *)request forCaller:(id)caller onSuccess:(SEL)successSelector onFailure:(SEL)failSelector;<br /><br />//HTTP Gets<br />+(NSURLRequest *)getURLRequestFor:(NSString *)urlString;<br />+(BOOL) doGet:(NSString *)urlString forCaller:(id)caller onSuccess:(SEL)successSelector onFailure:(SEL)failSelector;<br /><br />//Synchronized accessors<br />+(NSString *) doSynchronizedGet:(NSString *)urlString;<br />+(NSData *) doSynchronizedDataGet:(NSString *)urlString;<br />+(NSString *) doSynchronizedPostTo:(NSString *)urlString withRequest:(NSURLRequest*)request;<br />+(NSString *) doSynchronizedPostTo:(NSString *)urlString withData:(NSDictionary*)data;<br />+(NSString *) doSynchronizedPostTo:(NSString *)urlString withKeys:(NSArray*)postKeys andValues:(NSArray*)postValues;<br /><br />//Form/multipart (for file upload)<br />+(NSString *) doSynchronizedMultipartPostTo:(NSString*)urlString withData:(NSDictionary*)data fileKeys:(NSArray*)fileKeys;<br />+(NSString *) doSynchronizedMultipartPostTo:(NSString*)urlString withKeys:(NSArray*)keys andValues:(NSArray*)values fileKeys:(NSArray*)fileKeys;<br /><br />@end<br /></PRE><br /><br />...and here's where the magic happens:<br /><br /><PRE><br />//<br />// HttpHelper.m<br />//<br />// Created by Jon Evans on 04/09/09.<br />// Copyright 2009 Jon Evans. Apache 2.0 license.<br />//<br /><br />#import "HttpHelper.h"<br /><br /><br />@implementation HttpHelper<br /><br />static HttpHelper *singleton=nil;<br />static NSArray *latestCookies=nil;<br />static BOOL useCookies=NO;<br /><br /><br />#pragma mark -<br />#pragma mark Singleton methods<br /><br />+(HttpHelper *) getInstance {<br /> if (singleton==nil)<br /> singleton = [[[HttpHelper alloc] init] autorelease];<br /> return singleton;<br />}<br /><br />+(id)allocWithZone:(NSZone *)zone {<br /> if (singleton == nil) {<br /> singleton = [super allocWithZone:zone];<br /> return singleton;<br /> }<br /> return nil;<br />}<br /><br />-(id)copyWithZone:(NSZone *)zone {<br /> return self;<br />}<br /><br />-(id)retain {<br /> return self;<br />}<br /><br />-(NSUInteger)retainCount {<br /> return UINT_MAX;<br />}<br /><br />-(void)release {<br /> //pass<br />}<br /><br />-(id)autorelease {<br /> return self;<br />}<br /><br />- (void)dealloc {<br /> [super dealloc];<br />}<br /><br /><br />#pragma mark -<br />#pragma mark Convenience methods<br /><br />+(NSURLRequestCachePolicy)getCachePolicyFor:(NSString *)urlString {<br /> //Hived out to a separate method because we might fine-tune this later.<br /> return NSURLRequestUseProtocolCachePolicy;<br /> // return NSURLRequestReloadIgnoringCacheData;<br />}<br /><br /><br />#pragma mark -<br />#pragma mark Cookie handling<br /><br />+(void) useCookies:(BOOL)use<br />{<br /> useCookies=use;<br />}<br /><br />+(void) getCookiesFrom:(NSHTTPURLResponse*)response forURL:(NSURL*)url {<br /> if ([response class]==[NSHTTPURLResponse class])<br /> latestCookies = [NSHTTPCookie cookiesWithResponseHeaderFields:[response allHeaderFields] forURL:url];<br />}<br /><br />+(NSArray*) latestCookies {<br /> return latestCookies;<br />}<br /><br /><br /><br />#pragma mark -<br />#pragma mark HTTP Posts<br /><br />+(NSURLRequest*) buildPostRequestForURL:(NSString *)urlString withData:(NSDictionary*) data<br />{<br /> NSArray *keys = [data allKeys];<br /> NSMutableArray *values = [NSMutableArray arrayWithCapacity:[keys count]];<br /> for (NSString *key in keys) {<br /> NSString *value = [data objectForKey:key];<br /> [values addObject:(value ? [NSString stringWithFormat:@"%@",value] : @"")];<br /> }<br /> return [self buildRequestWithPostKeys:keys postValues:values urlString:urlString];<br />}<br /><br />+(NSURLRequest*) buildRequestWithPostKeys:(NSArray *) postKeys postValues:(NSArray *) postValues urlString:(NSString *)urlString {<br /> NSURL * url = [NSURL URLWithString:urlString];<br /> NSURLRequestCachePolicy policy = NSURLRequestReloadIgnoringCacheData; // we never want a cache of a post response<br /> NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:policy timeoutInterval:30.0];<br /> [request setHTTPMethod:@"POST"];<br /> <br /> if (useCookies && latestCookies!=nil && [latestCookies count]>0) {<br /> NSDictionary * headers = [NSHTTPCookie requestHeaderFieldsWithCookies:latestCookies];<br /> [request setAllHTTPHeaderFields:headers];<br /> }<br /> <br /> NSMutableData *paramData = [NSMutableData dataWithCapacity:8192];<br /> <br /> NSMutableString *params=[[NSMutableString alloc] initWithCapacity:1024];<br /> for (int i=0; i<[postValues count]; i++) {<br /> NSString *param = i>0 ? @"&" : @"";<br /> param = [param stringByAppendingFormat:@"%@=",[postKeys objectAtIndex:i]];<br /> [paramData appendData:[param dataUsingEncoding:NSUTF8StringEncoding]];<br /> <br /> NSObject* valueToPost = [postValues objectAtIndex:i];<br /> NSString *stringToPost = [valueToPost class]==[NSString class] ? (NSString*)valueToPost : [NSString stringWithFormat:@"%@",valueToPost];<br /> stringToPost = [stringToPost stringByReplacingOccurrencesOfString:@"&" withString:@"%26"];<br /> [paramData appendData:[stringToPost dataUsingEncoding:NSUTF8StringEncoding]];<br /> }<br /> <br /> NSString *msgLength = [NSString stringWithFormat:@"%d", [paramData length]];<br /> [request addValue: msgLength forHTTPHeaderField:@"Content-Length"];<br /> [request setHTTPBody: paramData];<br /> [params release];<br /> <br /> return request;<br />}<br /><br />+(BOOL) doPost:(NSURLRequest *)request forCaller:(id)caller onSuccess:(SEL)onSuccess onFailure:(SEL)onFailure {<br /> <br /> NSArray *keys = [NSArray arrayWithObjects:@"request", @"caller", @"onSuccess", @"onFailure", nil];<br /> NSArray *values = [NSArray arrayWithObjects:request, caller,<br /> [NSValue valueWithBytes:&onSuccess objCType:@encode(SEL)],<br /> [NSValue valueWithBytes:&onFailure objCType:@encode(SEL)],<br /> nil];<br /> NSDictionary *args = [NSDictionary dictionaryWithObjects:values forKeys: keys];<br /> [NSThread detachNewThreadSelector:@selector(doHttp:) toTarget:[self getInstance] withObject:args];<br /> return TRUE;<br />}<br /><br /><br />#pragma mark -<br />#pragma mark HTTP Gets<br /><br />+(NSURLRequest *)getURLRequestFor:(NSString *)urlString {<br /> NSURL *url = [NSURL URLWithString:urlString];<br /> NSURLRequestCachePolicy policy = [self getCachePolicyFor:urlString];<br /> NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:policy timeoutInterval:30.0];<br /> [request setHTTPMethod:@"GET"];<br /><br /> if (useCookies && latestCookies!=nil && [latestCookies count]>0) {<br /> NSDictionary * headers = [NSHTTPCookie requestHeaderFieldsWithCookies:latestCookies];<br /> [request setAllHTTPHeaderFields:headers];<br /> }<br /> return request;<br />}<br /><br />+(BOOL) doGet:(NSString *)urlString forCaller:(id)caller onSuccess:(SEL)onSuccess onFailure:(SEL)onFailure {<br /> NSURLRequest *request = [self getURLRequestFor:urlString];<br /> NSArray *keys = [NSArray arrayWithObjects:@"request", @"caller", @"onSuccess", @"onFailure", nil];<br /> NSArray *values = [NSArray arrayWithObjects:request, caller,<br /> [NSValue valueWithBytes:&onSuccess objCType:@encode(SEL)],<br /> [NSValue valueWithBytes:&onFailure objCType:@encode(SEL)],<br /> nil];<br /> NSDictionary *args = [NSDictionary dictionaryWithObjects:values forKeys: keys];<br /> NSThread* uploadThread = [[NSThread alloc] initWithTarget:[self getInstance] selector:@selector(doHttp:) object:args];<br /> [uploadThread start];<br /> [uploadThread release];<br /> return TRUE;<br />}<br /><br /><br />#pragma mark -<br />#pragma mark Internals<br /><br />-(BOOL) doHttp:(NSDictionary *)args<br />{<br /> @synchronized (self) {<br /> //autorelease pool<br /> NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];<br /> <br /> NSURLRequest *request = [args objectForKey:@"request"];<br /> NSObject *caller = [args objectForKey:@"caller"];<br /> <br /> SEL onSuccess;<br /> [[args objectForKey:@"onSuccess"] getValue:&onSuccess];<br /> SEL onFailure;<br /> [[args objectForKey:@"onFailure"] getValue:&onFailure];<br /> <br /> NSError *error=nil;<br /> NSHTTPURLResponse *response=nil;<br /> NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: &response error: &error ];<br /> NSString * responseString = [[[NSString alloc] initWithData: returnData encoding: NSUTF8StringEncoding] autorelease];<br /> <br /> NSString *errorString=nil;<br /> <br /> if (error)<br /> errorString = [NSString stringWithFormat:@"Error %@ '%@': %@",NSLocalizedString(@"loading page",nil), [request URL], [error localizedDescription]]; <br /> else if (response==nil || returnData==nil)<br /> errorString = [NSString stringWithFormat:@"Error - %@ %@",NSLocalizedString(@"No response from URL",nil), [request URL]];<br /> else if (response.statusCode!=200)<br /> errorString = [NSString stringWithFormat:@"Error - %@ %i %@ %@",NSLocalizedString(@"HTTP Error",nil), response.statusCode, NSLocalizedString(@"from URL",nil), [request URL]];<br /> <br /> if (errorString && [errorString length]>0) {<br /> NSLog(@"iTravel Error ",errorString);<br /> [caller performSelectorOnMainThread: onFailure withObject:errorString waitUntilDone:NO];<br /> }<br /> else {<br /> if (useCookies)<br /> [HttpHelper getCookiesFrom:response forURL:[request URL]];<br /> [caller performSelectorOnMainThread: onSuccess withObject:responseString waitUntilDone:YES];<br /> }<br /> [pool release];<br /> }<br /> return TRUE;<br />}<br /><br /><br />#pragma mark -<br />#pragma mark Synchronized methods<br /><br />+(NSString *) doSynchronizedGet:(NSString *)urlString {<br /> NSData *returnData = [HttpHelper doSynchronizedDataGet:urlString];<br /> if (!returnData)<br /> return [NSString stringWithFormat:@"Error: %@ %@",NSLocalizedString(@"No data received from server",nil), urlString];<br /> <br /> NSString * responseString = [[[NSString alloc] initWithData: returnData encoding: NSUTF8StringEncoding] autorelease];<br /> return responseString;<br />}<br /><br />+(NSData *) doSynchronizedDataGet:(NSString *)urlString {<br /> NSURLRequest *request = [self getURLRequestFor:urlString];<br /> NSHTTPURLResponse *response=nil;<br /> NSError *error=nil;<br /> NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];<br /> <br /> NSString *errorString=@"";<br /> if (error)<br /> errorString = [NSString stringWithFormat:@"Error %@ '%@': %@",NSLocalizedString(@"loading page",nil), urlString, [error localizedDescription]]; <br /> else if (response==nil || returnData==nil)<br /> errorString = [NSString stringWithFormat:@"Error - %@ %@",NSLocalizedString(@"No response from URL",nil), urlString];<br /> else if (response.statusCode!=200)<br /> errorString = [NSString stringWithFormat:@"Error - %@ %i %@ %@",NSLocalizedString(@"HTTP Error",nil), response.statusCode, NSLocalizedString(@"from URL",nil), urlString];<br /> <br /> if ([errorString length]>0)<br /> return [errorString dataUsingEncoding:NSUTF8StringEncoding];;<br /> <br /> if (useCookies)<br /> [HttpHelper getCookiesFrom:response forURL:[request URL]];<br /> <br /> return returnData;<br />}<br /><br />+(NSString *) doSynchronizedPostTo:(NSString *)urlString withData:(NSDictionary*)data {<br /> NSURLRequest *request = [self buildPostRequestForURL:urlString withData:data];<br /> return [self doSynchronizedPostTo:urlString withRequest:request];<br />}<br />+(NSString *) doSynchronizedPostTo:(NSString *)urlString withKeys:(NSArray*)postKeys andValues:(NSArray*)postValues {<br /> NSURLRequest *request = [self buildRequestWithPostKeys:postKeys postValues:postValues urlString:urlString];<br /> return [self doSynchronizedPostTo:urlString withRequest:request];<br />}<br />+(NSString *) doSynchronizedPostTo:(NSString *)urlString withRequest:(NSURLRequest*)request {<br /> NSHTTPURLResponse *response=nil;<br /> NSError *error=nil;<br /> NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];<br /> <br /> NSString *errorString=@"";<br /> if (error)<br /> errorString = [NSString stringWithFormat:@"Error - %@ '%@': %@",NSLocalizedString(@"HTTP Error posting to URL",nil), urlString, [error localizedDescription]]; <br /> else if (response==nil || returnData==nil)<br /> errorString = [NSString stringWithFormat:@"Error - %@ %@",NSLocalizedString(@"No response from URL",nil), urlString];<br /> else if (response.statusCode!=200)<br /> errorString = [NSString stringWithFormat:@"Error - %@ %i %@ %@",NSLocalizedString(@"HTTP Error",nil), response.statusCode, NSLocalizedString(@"from URL",nil), urlString];<br /> <br /> if ([errorString length]>0)<br /> return errorString;<br /> <br /> if (useCookies)<br /> [HttpHelper getCookiesFrom:response forURL:[request URL]];<br /> <br /> NSString * responseString = [[[NSString alloc] initWithData: returnData encoding: NSUTF8StringEncoding] autorelease];<br /> <br /> if ([[responseString lowercaseString] hasPrefix:@"error"])<br /> errorString = [NSString stringWithFormat:@"Error %@ %@ %@ %@",NSLocalizedString(@"message",nil), responseString, NSLocalizedString(@"from URL",nil), urlString];<br /> else if ([[responseString lowercaseString] hasPrefix:@"fail"])<br /> errorString = [NSString stringWithFormat:@"Error - %@ '%@' %@ %@",NSLocalizedString(@"Failure message",nil), responseString, NSLocalizedString(@"when posting to URL",nil), urlString];<br /> <br /> if ([errorString length]>0)<br /> return errorString;<br /> <br /> return responseString;<br />}<br /><br />+(NSString*) doSynchronizedMultipartPostTo:(NSString*)urlString withData:(NSDictionary*)data fileKeys:(NSArray*)fileKeys<br />{<br /> NSArray *keys = [data allKeys];<br /> NSMutableArray *values = [NSMutableArray arrayWithCapacity:[keys count]];<br /> for (NSString *key in keys) {<br /> NSString *value = [data objectForKey:key];<br /> [values addObject:(value ? value : @"")];<br /> }<br /> return [self doSynchronizedMultipartPostTo:urlString withKeys:keys andValues:values fileKeys:fileKeys];<br />}<br /><br />+(NSString *) doSynchronizedMultipartPostTo:(NSString*)urlString withKeys:(NSArray*)keys andValues:(NSArray*)values fileKeys:(NSArray*)fileKeys<br />{<br /> NSURL * url = [NSURL URLWithString:urlString];<br /> NSURLRequestCachePolicy policy = NSURLRequestReloadIgnoringCacheData; // we never want a cache of a post response<br /> NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:policy timeoutInterval:30.0];<br /> [request setHTTPMethod:@"POST"];<br /> <br /> NSString *boundary = [[NSProcessInfo processInfo] globallyUniqueString];<br /> [request setValue: [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary] forHTTPHeaderField:@"Content-Type"];<br /> <br /> NSMutableData *postBody = [NSMutableData dataWithCapacity:65536];<br /> for (int i=0; i<[keys count]; i++) {<br /> NSString *key = [keys objectAtIndex:i];<br /> NSObject *value = [values objectAtIndex:i];<br /><br /> if (value && fileKeys && [fileKeys containsObject:key]) {<br /> [postBody appendData: [[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];<br /> if ([value isKindOfClass:[NSString class]]) {<br /> NSString *valueString = (NSString*)value;<br /> if ([valueString length]>0) {<br /> NSRange slashRange = [valueString rangeOfString:@"/" options:NSBackwardsSearch];<br /> NSString *fileName = slashRange.location!=NSNotFound && ![valueString hasSuffix:@"/"]<br /> ? [valueString substringFromIndex:slashRange.location+1]<br /> : valueString;<br /> [postBody appendData: [[NSString stringWithFormat: @"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", key, fileName] dataUsingEncoding:NSUTF8StringEncoding]];<br /> [postBody appendData: [[NSString stringWithFormat: @"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];<br /> [postBody appendData: [NSData dataWithContentsOfMappedFile:valueString]];<br /> }<br /> }<br /> else if ([value isKindOfClass:[NSURL class]]) {<br /> NSURL *fileURL = (NSURL*)value;<br /> [postBody appendData: [[NSString stringWithFormat: @"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", key, [fileURL lastPathComponent]] dataUsingEncoding:NSUTF8StringEncoding]];<br /> [postBody appendData: [[NSString stringWithFormat: @"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];<br /> [postBody appendData: [NSData dataWithContentsOfURL:fileURL]];<br /> }<br /> else if ([value isKindOfClass:[NSData class]]) {<br /> [postBody appendData: [[NSString stringWithFormat: @"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", key, key] dataUsingEncoding:NSUTF8StringEncoding]];<br /> [postBody appendData: [[NSString stringWithFormat: @"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];<br /> [postBody appendData: (NSData*)value];<br /> }<br /> }<br /> else {<br /> [postBody appendData:[[NSString stringWithFormat: @"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];<br /> [postBody appendData:[[NSString stringWithFormat: @"Content-Disposition: form-data; name=\"%@\"\r\n",key] dataUsingEncoding:NSUTF8StringEncoding]];<br /> [postBody appendData: [[NSString stringWithFormat: @"Content-Type: text/plain;charset=utf-8\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];<br /> NSString *valueString = [NSString stringWithFormat: @"%@", value];<br /> [postBody appendData:[valueString dataUsingEncoding:NSUTF8StringEncoding]];<br /> }<br /> [postBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];<br /> }<br /> [postBody appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];<br /> <br /> NSString *msgLength = [NSString stringWithFormat:@"%d", [postBody length]];<br /> [request addValue: msgLength forHTTPHeaderField:@"Content-Length"];<br /> [request setHTTPBody:postBody];<br /> <br /> NSHTTPURLResponse *response=nil;<br /> NSError *error=nil;<br /> NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];<br /> <br /> NSString *errorString=@"";<br /> if (error)<br /> errorString = [NSString stringWithFormat:@"Error - %@ '%@': %@",NSLocalizedString(@"HTTP Error posting to URL",nil), urlString, [error localizedDescription]]; <br /> else if (response==nil || returnData==nil)<br /> errorString = [NSString stringWithFormat:@"Error - %@ %@",NSLocalizedString(@"No response from URL",nil), urlString];<br /> else if (response.statusCode!=200)<br /> errorString = [NSString stringWithFormat:@"Error - %@ %i %@ %@",NSLocalizedString(@"HTTP Error",nil), response.statusCode, NSLocalizedString(@"from URL",nil), urlString];<br /> <br /> if ([errorString length]>0)<br /> return errorString;<br /> <br /> NSString * responseString = [[[NSString alloc] initWithData: returnData encoding: NSUTF8StringEncoding] autorelease];<br /> <br /> if ([[responseString lowercaseString] hasPrefix:@"error"])<br /> errorString = [NSString stringWithFormat:@"Error %@ %@ %@ %@",NSLocalizedString(@"message",nil), responseString, NSLocalizedString(@"from URL",nil), urlString];<br /> else if ([[responseString lowercaseString] hasPrefix:@"fail"])<br /> errorString = [NSString stringWithFormat:@"Error - %@ '%@' %@ %@",NSLocalizedString(@"Failure message",nil), responseString, NSLocalizedString(@"when posting to URL",nil), urlString];<br /> <br /> if ([errorString length]>0)<br /> return errorString;<br /> <br /> if (useCookies)<br /> [HttpHelper getCookiesFrom:response forURL:[request URL]];<br /> return responseString;<br />}<br /><br /><br />@end<br /></PRE>Jonhttp://www.blogger.com/profile/17475458068193351080noreply@blogger.com28tag:blogger.com,1999:blog-259176237881102296.post-11044249110164385982010-11-05T18:10:00.000-07:002010-11-05T18:13:26.737-07:00Pronoid Android sleepsAs you may have noticed, if your eyes for Nothing are as keen as Alice's, there hasn't been a whole lot of activity 'round here of late; that's because I've been up to my nose in paying app work, most of which I can't write about in public for obvious non-disclosure-agreement reasons. But I hope to find some pet-project time come the new year, so check back in then -<br /><br />JonJonhttp://www.blogger.com/profile/17475458068193351080noreply@blogger.com13tag:blogger.com,1999:blog-259176237881102296.post-9024970835259417022010-09-19T18:54:00.000-07:002010-11-05T18:12:25.294-07:00Of Zips and the InternetSo of late I've been working on adding the ability to download a complete snapshot of Wikitravel to my <a href="http://itravelfree.net/">iTravel app</a>. And I've finally got it working, for both Android and iPhone - but there was many a glitch along the way.<br /><br />First off: downloading. Now that part's actually pretty easy. You know what's tricky? Working out whether you <i>can</i> download. Both Android and iPhone bury their "hey, am I connected to the Internet, and if so, how?" API facilities deep in their documentation.<br /><br />To be fair, Android isn't so bad:<br /><PRE><br /> public static boolean CheckInternetConnection(Context context) {<br /> if (context==null)<br /> return false;<br /> ConnectivityManager connec = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);<br /> return ( connec.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnectedOrConnecting() ||<br /> connec.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting() );<br /> }<br /></PRE><br /><br />...straightforward enough, just not as well-documented as it could be.<br /><br />The iPhone, though. Well. Sheesh. The way you actually do it is through seriously byzantine and messy C code. Because most people don't want to have to deal with that, Apple provides a reference implementation - but do they tell you about this anywhere in their documentation? No, they do not. Thank heavens for <a href="http://stackoverflow.com/">Stack Overflow</a>, which pointed me to <a href="http://developer.apple.com/library/ios/#samplecode/Reachability/Introduction/Intro.html">Reachability</a>.<br /><br />But wait, there's less: the old version has a very simple interface:<br /><PRE><br />+(BOOL) serverReachable {<br /> Reachability *reachability = [Reachability reachabilityWithHostName:@"http://itravelapp.appspot.com/"];<br /> return [reachability currentReachabilityStatus]!=NotReachable;<br />}<br /></PRE><br /><br />but the new version requires you to set up a whole asynchronous notification framework. OK, so it probably works better, and it's not <i>too</i> onerous:<br /><br /><PRE><br />-(void) initiateReachability {<br /> // check for internet connection<br /> [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkNetworkStatus:) name:kReachabilityChangedNotification object:nil];<br /> <br /> internetReachable = [[Reachability reachabilityForInternetConnection] retain];<br /> [internetReachable startNotifier];<br /> <br /> // check if a pathway to my server exists<br /> serverReachable = [[Reachability reachabilityWithHostName: @"itravelapp.appspot.com"] retain];<br /> [serverReachable startNotifier];<br />}<br /><br />+(void) initiateReachability {<br /> [[self getInstance] initiateReachability];<br />}<br /><br />- (void) checkNetworkStatus:(NSNotification *)notice<br />{<br /> // called after network status changes<br /> <br /> NetworkStatus internetStatus = [internetReachable currentReachabilityStatus];<br /> internetActive = internetStatus != NotReachable;<br /> <br /> NetworkStatus serverStatus = [serverReachable currentReachabilityStatus];<br /> serverActive = serverStatus != NotReachable;<br />}<br /><br />-(BOOL) serverReachable {<br /> return serverActive;<br />}<br /><br />+(BOOL) serverReachable {<br /> return [[self getInstance] serverReachable];<br />}<br /></PRE><br /><br />But still, compare and contrast to the Android version above. Oh, Apple. Whatever were you thinking?<br /><br />OK. So you've got the Internet. You've downloaded your zip files. (Yes, <i>files</i>, plural; one of my early problems is that both Androids and iPhones choke and die on 100MB zip files, due to their memory constraints. But five 20MB zip files, handled consecutively, no problem.)<br /><br />Now how do you open them?<br /><br />In Android, it's easy enough: java.util.zip.ZipFile and java.util.zip.ZipEntry. (In fact, it's easy - and fast - enough that I don't even unpack those files; I just access data from within them on the fly.) On the iPhone, though, although the <b>libz.1.2.3.dylib</b> zlib framework is provided, actually working with it requires some serious low-level C chops, and mine are rusty beyond belief.<br /><br />But that's OK! Because others' aren't, and we live in an open-source world. I just went out and downloaded Karl Mostowski's truly excellent <a href="http://bitbucket.org/kolpanic/zipkit/wiki/Home">ZipKit</a> framework, and used it. I had some trouble using it as a static library... so I gave up and just included his source in my project. And it worked like a charm. A diamond-studded, streamlined, memory-miserly charm. Thanks, Karl!<br /><br />Here's an example of it in action:<br /><PRE><br />-(void) doUnpacking {<br /> [Util showActivity];<br /> [self startProgressView];<br /> self.title=@"Unpacking ...";<br /> NSThread* unpackThread = [[NSThread alloc] initWithTarget:self selector:@selector(launchUnpacking) object:nil];<br /> [unpackThread start];<br /> [unpackThread release];<br />}<br /><br />-(void) launchUnpacking {<br /> NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];<br /><br /> int zipFiles = [[Settings getBulkZipFiles] intValue];<br /> if (zipFiles > 0)<br /> [Settings setBulkUnpackedFiles:0];<br /><br /> for (int i=0; i < zipFiles; i++) {<br /> NSString *titleString = [NSString stringWithFormat:@"Unpacking %d of %d", i+1, zipFiles];<br /> [self performSelectorOnMainThread:@selector(setTitle:) withObject:titleString waitUntilDone:YES];<br /> NSAutoreleasePool *pool2 = [[NSAutoreleasePool alloc] init];<br /> NSString *fileName = [NSString stringWithFormat:@"/iTravelDump%d.zip",i];<br /> NSString *dumpPath = [[Util getBulkDownloadPath] stringByAppendingPathComponent:fileName];<br /> ZKFileArchive *archive = [ZKFileArchive archiveWithArchivePath:dumpPath];<br /> archive.delegate = self;<br /> totalFiles = [archive.centralDirectory count];<br /> currentFile=0;<br /> [archive inflateToDirectory:[[Util getBulkDownloadPath] stringByAppendingPathComponent:@"temp"] usingResourceFork:NO];<br /> archive=nil;<br /> [pool2 release];<br /> [Settings setBulkUnpackedFiles:[Settings getBulkUnpackedFiles]+totalFiles];<br /> }<br /><br /> //done!<br /> [self performSelectorOnMainThread:@selector(unpackingFinished) withObject:nil waitUntilDone:NO];<br /> [pool release];<br />}<br /><br />//ZKArchive delegate<br />- (void) onZKArchive:(ZKArchive *) archive willUnzipPath:(NSString *) path {<br /> if (progressView) {<br /> float currentLength = (float)++currentFile;<br /> float totalSize = (float)totalFiles;<br /> float fraction = (float)currentLength/totalSize;<br /> [progressView setProgress:fraction];<br /> }<br />}<br /><br />-(void)unpackingFinished {<br /> [Util stopShowingActivity];<br /> [self stopProgressView];<br /> [Settings setLastBulkUnpack:[NSDate date]];<br /> [Settings save];<br /> self.title=@"Unpacking Complete";<br /> [self loadHTML];<br />}<br /><br /></PRE>Jonhttp://www.blogger.com/profile/17475458068193351080noreply@blogger.com22tag:blogger.com,1999:blog-259176237881102296.post-77441958818375941952010-08-12T06:26:00.000-07:002010-08-12T06:31:14.533-07:00App Localizer 2.0, now with more iPhoneQuick update: the <a href="http://itravelapp.appspot.com/static/localizer.html">new App Localizer</a> now handles both Android and iPhone strings files.Jonhttp://www.blogger.com/profile/17475458068193351080noreply@blogger.com329tag:blogger.com,1999:blog-259176237881102296.post-55529860026306060052010-07-26T12:56:00.000-07:002010-07-26T13:08:28.199-07:00Localize your Android apps via Google Translate, the easy way!Smartphones are increasingly used all over the globe, and I expect English to be a minority language among their users pretty soon. Fortunately, both Android and the iPhone are designed from the ground up for multilanguage localization. It's basically a two-step process for both:<br /><OL><br /><LI>Move all the strings you show your user from code into a strings file. You do this by using <b>activity.getString()</b> in Android, and the NSLocalizedString macro followed by <a href="http://www.switchonthecode.com/tutorials/a-simple-localization-example-for-the-iphone">a bit of command-line voodoo</a> in Objective-C.<br /><LI>Translate the strings file into another language.<br /></OL><br /><br />There are various translation services you can pay for step 2. And if you're serious about it being a good translation, you probably want to do that. But for a first iteration, or a quick-and-dirty app, why not just use Google Translate?<br /><br />"Because that would be really tedious" is one answer. Aha, but there is a JavaScript API for Google Translate! And hence I give you this one-page, two-click solution for translating an Android strings file into another language:<br /><PRE><br /><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"><br /><head><br /> <link type="text/css" rel="stylesheet" href="/static/main.css" /><br /> <title>App Localizer</title><br /></head><br /><br /><script type="text/javascript" src="http://www.google.com/jsapi"><br /></script><br /><script type="text/javascript"><br /> google.load("language", "1");<br /></script><br /><br /><body><br /> <div id="wrapper"><br /> <table width=800><tr><br /> <td align=left><h3><a href="/">iTravelFree.net</a></h3></td><br /> <td align=right><img src="http://code.google.com/appengine/images/appengine-silver-120x30.gif"<br />alt="Powered by Google App Engine" height=30 width=120/></td><br /> </tr><tr><td colspan=2><HR></td><br /> </tr></table><br /><br /> <div id="content"><br /> <table width=800><tr><td><br /><br /><H3>Localizer</H3><br /><form name="localize" onsubmit="return doGo();"><br /> Translate the<br /> <select name="xmlType"><br /> <option>Android</option><br /> <option>iPhone</option><br /> </select><br /> string file on the top from<br /> <select name="languageFrom"><br /> <option value="en" selected="true">English</option><br /> <option value="fr">French</option><br /> <option value="de">German</option><br /> </select><br /> to<br /> <select name="languageTo"><br /> <option value="ar">Arabic</option><br /> <option value="zh">Chinese</option><br /> <option value="nl">Dutch</option><br /> <option value="en">English</option><br /> <option value="fi">Finnish</option><br /> <option value="fr">French</option><br /> <option value="de">German</option><br /> <option value="he">Hebrew</option><br /> <option value="hi">Hindi</option><br /> <option value="it">Italian</option><br /> <option value="ja">Japanese</option><br /> <option value="ko">Korean</option><br /> <option value="pt">Portuguese</option><br /> <option value="ru">Russian</option><br /> <option value="es">Spanish</option><br /> <option value="sv">Swedish</option><br /> </select><br /> <input type="submit" name="go" value="Translate"><br /> <textarea name="inbox" cols=85 rows=11></textarea><br /> <textarea name="outbox" cols=85 rows=11></textarea><br /></form><br /><br /> </td></tr></table><br /> </div><br /> <div id="footer"><br /> <table width=800><tr><td colspan=2><HR/></td></tr><tr><td align=right><br /> <a href="/">Home</a> | <a href="/">App</a> | <a href="/map">Map</a><br /> </td></tr></table><br /> </div><br /> </div><br /><br /> <script type="text/javascript"><br /> var output;<br /><br /> function doGo() {<br /> document.localize.outbox.value="Parsing, please wait...";<br /><br /> if (document.localize.xmlType.value == "Android") {<br /> output = '<?xml version="1.0" encoding="utf-8"?>\n<resources>';<br /> }<br /> else {<br /> output = 'TODO: iPhone';<br /> }<br /><br /> // parse and translate the relevant values out of the XML<br /> if (window.DOMParser) //<br /> {<br /> parser=new DOMParser();<br /> xmlDoc=parser.parseFromString(document.localize.inbox.value,"text/xml");<br /> }<br /> else // Internet Explorer<br /> {<br /> xmlDoc=new ActiveXObject("Microsoft.XMLDOM");<br /> xmlDoc.async="false";<br /> xmlDoc.loadXML(document.localize.inbox.value);<br /> }<br /><br /> if (document.localize.xmlType.value == "Android") {<br /> stringElements = xmlDoc.getElementsByTagName("string");<br /> handleNextVal(stringElements, 0);<br /> }<br /> else {<br /> //TODO: iPhone<br /> }<br /> return false;<br /> }<br /> <br /> function handleNextVal(elements, index) {<br /> if (index>=elements.length)<br /> return doFinish();<br /><br /> if (index>0)<br /> output+= '</string>'<br /><br /> element = stringElements[index];<br /> name = element.attributes.getNamedItem("name").nodeValue;<br /> initialVal = element.childNodes[0].nodeValue;<br /> output+= '\n\t<string name="'+name+'">'<br /> google.language.translate(initialVal,<br /> document.localize.languageFrom.value,<br /> document.localize.languageTo.value,<br /> function(result) {<br /> if (result.error)<br /> output+=initialVal;<br /> else<br /> output+=result.translation.replace("'","'");<br /> handleNextVal(elements, index+1);<br /> });<br /> }<br /> <br /> function doFinish() {<br /> if (document.localize.xmlType.value == "Android") {<br /> output+= '</string>\n</resources>';<br /> }<br /> else {<br /> //TODO: iPhone<br /> }<br /> document.localize.outbox.value=output;<br /> return false;<br /> }<br /> </script><br /></body><br /></html><br /></PRE><br /><br />There now. Was that so hard? Just paste your initial strings file into the top text box, select your From and To language, hit "Translate", sit back for 30 seconds, let Google Translate work its magic, <i>et voila</i>: your translated strings file appears down below.<br /><br />Still too lazy to get it up and running yourself? Fine, here's a fully functional version running on my iTravelFree app's App Engine service:<br /><a href="http://itravelapp.appspot.com/static/localizer.html">http://itravelapp.appspot.com/static/localizer.html</a><br /><br />Right now it only handles Android strings-file syntax, but I'll be adding iPhone soon enough. (And really, if you know <i>anything</i> about JavaScript and XML, it won't be hard for you to customize it yourself.)<br /><br />Hope y'all find it useful -<br /><br />JonJonhttp://www.blogger.com/profile/17475458068193351080noreply@blogger.com10tag:blogger.com,1999:blog-259176237881102296.post-56629724984193086162010-06-16T11:36:00.000-07:002010-06-17T08:24:23.896-07:00HttpHelper for allWell, that's flattering: the lead developer of WordPress for iOS (WordPress is <a href="http://en.wikipedia.org/wiki/WordPress">the world's most popular blogging software</a>) just emailed me, saying nice things about my previously-posted HttpHelper class, and asking for permission to use it in their project.<br /><br />And why stop with them? So I hereby formally release HttpHelper under the <a href="http://en.wikipedia.org/wiki/Apache_License">Apache License 2.0</a>, for anyone to use. I've made a few tweaks to the class since I last posted it - one bug fix, and some synchronous accessors for use when you're already in a background thread - so here it is in its entirety:<br /><br /><b>HttpHelper.h</b><br /><br /><PRE><br />// HttpHelper.h<br />// Created by Jonathan Evans on 04/09/09.<br />// Copyright 2009 Jonathan Evans.<br /><br />#import <Foundation/Foundation.h><br /><br /><br />@interface HttpHelper : NSObject {<br />}<br />+(NSURLRequest *) buildRequestWithPostKeys:(NSArray *) postKeys postValues:(NSArray *) postValues urlString:(NSString *)urlString;<br />+(BOOL) doPost:(NSURLRequest *)request forCaller:(id)caller onSuccess:(SEL)successSelector onFailure:(SEL)failSelector;<br />-(BOOL) doHttp:(NSDictionary *)args;<br /><br />+(NSURLRequestCachePolicy)getCachePolicyFor:(NSString *)urlString;<br />+(NSURLRequest *)getURLRequestFor:(NSString *)urlString;<br />+(BOOL) doGet:(NSString *)urlString forCaller:(id)caller onSuccess:(SEL)successSelector onFailure:(SEL)failSelector;<br />+(NSString *) doSynchronizedGet:(NSString *)urlString;<br />+(NSData *) doSynchronizedDataGet:(NSString *)urlString;<br />+(NSString *) doSynchronizedPostTo:(NSString *)urlString withKeys:(NSArray*)postKeys andValues:(NSArray*)postValues;<br /><br />@end<br /></PRE><br /><br /><b>HttpHelper.m</b><br /><br /><PRE><br />// HttpHelper.m<br />// Created by Jonathan Evans on 04/09/09.<br />// Copyright 2009 Jonathan Evans.<br />//<br /><br />#import "HttpHelper.h"<br /><br /><br />@implementation HttpHelper<br /><br />static HttpHelper *singleton=nil;<br /><br />#pragma mark -<br />#pragma mark Singleton methods<br /><br />+(HttpHelper *) getInstance {<br /> if (singleton==nil)<br /> singleton = [[[HttpHelper alloc] init] autorelease];<br /> return singleton;<br />}<br /><br />+(id)allocWithZone:(NSZone *)zone {<br /> if (singleton == nil) {<br /> singleton = [super allocWithZone:zone];<br /> return singleton;<br /> }<br /> return nil;<br />}<br /><br />-(id)copyWithZone:(NSZone *)zone {<br /> return self;<br />}<br /><br />-(id)retain {<br /> return self;<br />}<br /><br />-(unsigned)retainCount {<br /> return UINT_MAX;<br />}<br /><br />-(void)release {<br /> //pass<br />}<br /><br />-(id)autorelease {<br /> return self;<br />}<br /><br />- (void)dealloc {<br /> [super dealloc];<br />}<br /><br />#pragma mark -<br />#pragma mark Business logic<br /><br />+(NSURLRequest*) buildRequestWithPostKeys:(NSArray *) postKeys postValues:(NSArray *) postValues urlString:(NSString *)urlString {<br /> NSURL * url = [NSURL URLWithString:urlString];<br /> NSURLRequestCachePolicy policy = NSURLRequestReloadIgnoringCacheData; // we never want a cache of a post response<br /> NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:policy timeoutInterval:30.0]; //TODO: extend timeout<br /> [request setHTTPMethod:@"POST"];<br /> <br /> NSMutableData *paramData = [NSMutableData dataWithCapacity:8192];<br /> <br /> NSMutableString *params=[[NSMutableString alloc] initWithCapacity:1024];<br /> for (int i=0; i<[postValues count]; i++) {<br /> NSObject* valueToPost = [postValues objectAtIndex:i];<br /> if (i>0)<br /> [params appendString:@"&"]; <br /> [params appendString:[postKeys objectAtIndex:i]];<br /> [params appendString:@"="];<br /> [params appendString:[NSString stringWithFormat:@"%@",valueToPost]];<br /> }<br /> <br /> [paramData appendData:[params dataUsingEncoding:NSUTF8StringEncoding]];<br /> <br /> NSString *msgLength = [NSString stringWithFormat:@"%d", [paramData length]];<br /> [request addValue: msgLength forHTTPHeaderField:@"Content-Length"];<br /> [request setHTTPBody: paramData];<br /> [params release];<br /> <br /> return request;<br />}<br /><br />+(BOOL) doPost:(NSURLRequest *)request forCaller:(id)caller onSuccess:(SEL)onSuccess onFailure:(SEL)onFailure {<br /> <br /> NSArray *keys = [NSArray arrayWithObjects:@"request", @"caller", @"onSuccess", @"onFailure", nil];<br /> NSArray *values = [NSArray arrayWithObjects:request, caller,<br /> [NSValue valueWithBytes:&onSuccess objCType:@encode(SEL)],<br /> [NSValue valueWithBytes:&onFailure objCType:@encode(SEL)],<br /> nil];<br /> NSDictionary *args = [NSDictionary dictionaryWithObjects:values forKeys: keys];<br /> NSThread* uploadThread = [[NSThread alloc] initWithTarget:[self getInstance] selector:@selector(doHttp:) object:args];<br /> [uploadThread start];<br /> [uploadThread release];<br /> return TRUE;<br />}<br /><br />+(NSURLRequestCachePolicy)getCachePolicyFor:(NSString *)urlString {<br /> //Hived out to a separate method because we might fine-tune this later.<br /> return NSURLRequestUseProtocolCachePolicy;<br /> // return NSURLRequestReloadIgnoringCacheData;<br />}<br /><br />+(NSURLRequest *)getURLRequestFor:(NSString *)urlString {<br /> NSURL *url = [NSURL URLWithString:urlString];<br /> NSURLRequestCachePolicy policy = [self getCachePolicyFor:urlString];<br /> NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:policy timeoutInterval:30.0];<br /> return request;<br />}<br /><br />+(BOOL) doGet:(NSString *)urlString forCaller:(id)caller onSuccess:(SEL)onSuccess onFailure:(SEL)onFailure {<br /> NSURLRequest *request = [self getURLRequestFor:urlString];<br /> NSArray *keys = [NSArray arrayWithObjects:@"request", @"caller", @"onSuccess", @"onFailure", nil];<br /> NSArray *values = [NSArray arrayWithObjects:request, caller,<br /> [NSValue valueWithBytes:&onSuccess objCType:@encode(SEL)],<br /> [NSValue valueWithBytes:&onFailure objCType:@encode(SEL)],<br /> nil];<br /> NSDictionary *args = [NSDictionary dictionaryWithObjects:values forKeys: keys];<br /> NSThread* uploadThread = [[NSThread alloc] initWithTarget:[self getInstance] selector:@selector(doHttp:) object:args];<br /> [uploadThread start];<br /> [uploadThread release];<br /> return TRUE;<br />}<br /><br />-(BOOL) doHttp:(NSDictionary *)args<br />{<br /> @synchronized (self) {<br /> //autorelease pool<br /> NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];<br /> <br /> NSURLRequest *request = [args objectForKey:@"request"];<br /> NSObject *caller = [args objectForKey:@"caller"];<br /> <br /> SEL onSuccess;<br /> [[args objectForKey:@"onSuccess"] getValue:&onSuccess];<br /> SEL onFailure;<br /> [[args objectForKey:@"onFailure"] getValue:&onFailure];<br /> <br /> NSError *error=nil;<br /> NSHTTPURLResponse *response=nil;<br /> NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: &response error: &error ];<br /> NSString * responseString = [[[NSString alloc] initWithData: returnData encoding: NSUTF8StringEncoding] autorelease];<br /><br /> NSString *errorString=nil;<br /><br /> if (error)<br /> errorString = [NSString stringWithFormat:@"HTTP error from %@: %@", [request URL], [error localizedDescription]];<br /> else if (response==nil || returnData==nil)<br /> errorString = [NSString stringWithFormat:@"No response from URL %@",[request URL]];<br /> else if (response.statusCode!=200)<br /> errorString = [NSString stringWithFormat:@"Server error from URL %@",[request URL]];<br /> <br /> if (errorString && [errorString length]>0) {<br /> NSLog(@"iTravel Error ",errorString);<br /> [caller performSelectorOnMainThread: onFailure withObject:errorString waitUntilDone:NO];<br /> }<br /> else<br /> [caller performSelectorOnMainThread: onSuccess withObject:responseString waitUntilDone:YES];<br /> [pool release];<br /> }<br /> return TRUE;<br />}<br /><br />+(NSString *) doSynchronizedGet:(NSString *)urlString {<br /> NSData *returnData = [HttpHelper doSynchronizedDataGet:urlString];<br /> if (!returnData)<br /> return [NSString stringWithFormat: @"Error: No data received from server",urlString];<br /> <br /> NSString * responseString = [[[NSString alloc] initWithData: returnData encoding: NSUTF8StringEncoding] autorelease];<br /> return responseString;<br />}<br /><br />+(NSData *) doSynchronizedDataGet:(NSString *)urlString {<br /> NSURLRequest *request = [self getURLRequestFor:urlString];<br /> NSHTTPURLResponse *response=nil;<br /> NSError *error=nil;<br /> NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];<br /> <br /> NSString *errorString=@"";<br /> if (error)<br /> errorString = [NSString stringWithFormat:@"Error loading page: %@", urlString, [error localizedDescription]];<br /> else if (response==nil || returnData==nil)<br /> errorString = [NSString stringWithFormat:@"Error - No response from URL %@", urlString];<br /> else if (response.statusCode!=200)<br /> errorString = [NSString stringWithFormat:@"Error - HTTP Error %i from URL %@", response.statusCode, urlString];<br /> <br /> if ([errorString length]>0)<br /> return [errorString dataUsingEncoding:NSUTF8StringEncoding];<br /> <br /> return returnData;<br />}<br /><br />+(NSString *) doSynchronizedPostTo:(NSString *)urlString withKeys:(NSArray*)postKeys andValues:(NSArray*)postValues {<br /> NSURLRequest *request = [self buildRequestWithPostKeys:postKeys postValues:postValues urlString:urlString];<br /> NSHTTPURLResponse *response=nil;<br /> NSError *error=nil;<br /> NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];<br /> <br /> NSString *errorString=@"";<br /> if (error)<br /> errorString = [NSString stringWithFormat:@"Error - HTTP Error posting to URL %@: %@", urlString, [error localizedDescription]]; <br /> else if (response==nil || returnData==nil)<br /> errorString = [NSString stringWithFormat:@"Error - No response from URL %@", urlString];<br /> else if (response.statusCode!=200)<br /> errorString = [NSString stringWithFormat:@"Error - HTTP Error %i from URL %@", response.statusCode, urlString];<br /> <br /> if ([errorString length]>0)<br /> return errorString;<br /> <br /> NSString * responseString = [[[NSString alloc] initWithData: returnData encoding: NSUTF8StringEncoding] autorelease];<br /> <br /> if ([[responseString lowercaseString] hasPrefix:@"error"])<br /> errorString = [NSString stringWithFormat:@"Error message %@ from URL %@",responseString, urlString];<br /> else if ([[responseString lowercaseString] hasPrefix:@"fail"])<br /> errorString = [NSString stringWithFormat:@"Error - Failure message '%@' when posting to URL %@", responseString, urlString];<br /> <br /> if ([errorString length]>0)<br /> return errorString;<br /> <br /> return nil; //indicates success<br />}<br /><br />@end<br /></PRE><br /><br /><b>How To Use It</b><br /><br />The three chief asynchronous interface methods are, for a GET -<br /><br /><PRE><br />+(BOOL) doGet:(NSString *)urlString forCaller:(id)caller onSuccess:(SEL)onSuccess onFailure:(SEL)onFailure<br /></PRE><br /><br />and for a POST -<br /><br /><PRE><br />+(NSURLRequest*) buildRequestWithPostKeys:(NSArray *) postKeys postValues:(NSArray *) postValues urlString:(NSString *)urlString<br /><br />+(BOOL) doPost:(NSURLRequest *)request forCaller:(id)caller onSuccess:(SEL)onSuccess onFailure:(SEL)onFailure {<br /></PRE><br /><br />I'll give you an example of the former first, as it's easier. The call itself is perfectly straightforward:<br /><br /><PRE><br /> NSMutableString *urlString = [NSMutableString stringWithCapacity:128];<br /> [urlString appendString:[Util getSearchPageURL]];<br /> [urlString appendString:@"?locale="];<br /> [urlString appendString:[UserSettings getLanguage]];<br /> [urlString appendString:@"&searchTerms="];<br /> [urlString appendString:[searchBar.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];<br /> [HttpHelper doGet:urlString forCaller:self onSuccess:@selector(parseSearchResults:) onFailure:@selector(searchFailed:)];<br /></PRE><br /><br />Not, however, the two "@selector" arguments. These must be methods on the caller, and they better expect an NSString* and an NSError*, respectively, as arguments. (Or they can take an NSObject* and cast from there, I suppose, but why bother, right?)<br /><br />Inside HttpHelper we have to wrap the selectors in NSValues to pass them from method to method, which is a bit annoying, but hey, we only have to do it once.<br /><br />To call a POST, by comparison:<br /><PRE><br /> NSArray *postKeys = [NSArray arrayWithObjects:@"title", @"location", @"comments", @"pageUri", @"sectionName", @"sectionNumber", @"listingName", nil];<br /> NSArray *postValues = [NSArray arrayWithObjects:note.title, [note locationString], note.body, note.pageUri, note.sectionName, note.sectionNumber, note.listingName, nil];<br /> NSURLRequest *request = [HttpHelper buildRequestWithPostKeys:postKeys postValues:postValues urlString:[Util getUploadNoteURL]];<br /> [HttpHelper doPost:request forCaller:self onSuccess:@selector(onUploadSuccess) onFailure:@selector(onUploadError:)];<br /></PRE><br /><br />Note that "onUploadSuccess" here doesn't take an argument - I don't care about the web site's response, the fact of success is all that matters. OK, dubious wisdom that, but the example is relevant to show that the selector methods don't actually have to accept arguments.<br /><br />We launch a new thread every time we call these methods, so we have to be careful lest we run into concurrency problems. So we synchronize the actual HTTP calls in the "doHttp:" method, which is the one place in the app where we actually go out and connect to the big bad scary Internet.<br /><br />The synchronous methods are simple enough that I don't think they require examples:<br /><br /><PRE><br />+(NSString *) doSynchronizedGet:(NSString *)urlString;<br />+(NSData *) doSynchronizedDataGet:(NSString *)urlString;<br />+(NSString *) doSynchronizedPostTo:(NSString *)urlString withKeys:(NSArray*)postKeys andValues:(NSArray*)postValues;<br /></PRE><br /><br />The DataGet is in case you want NSData instead of an NSString - if you're loading an image, for instance.Jonhttp://www.blogger.com/profile/17475458068193351080noreply@blogger.com17tag:blogger.com,1999:blog-259176237881102296.post-58338025909899282072010-04-16T06:52:00.001-07:002010-04-16T07:04:52.208-07:00My love/hate relationship with the iPhone SDKThere is a lot to hate about the iPhone SDK. But there's also a lot to love.<br /><br />My app iTravel goes out and gets Wikitravel pages, and then gets subpages in the background. (eg if you ask for "New York City", it'll also go out and get "Manhattan", "Upper West Side", etc.) It also plots listings (sights, restaurants, etc.) for all these pages on a map. I wanted the background thread that was loading this data to automatically a new page's listings to the map, if the viewer was using one; so they can go to "New York City", go to the map, and then watch Manhattan slowly get barnacled by map annotations, one neighbourhood at a time.<br /><br />I thought this was going to be difficult. I couldn't have been more wrong. Here's the background-thread code, in its entirety:<br /><br /><PRE><br />-(void) refreshMapIfActive {<br /> UIApplication *app = [UIApplication sharedApplication];<br /> iTravelRightAppDelegate *appDelegate = app.delegate;<br /> UINavigationController *controller = [appDelegate navigationController];<br /> NSArray *viewControllers = [controller viewControllers];<br /> UIViewController *currentController = [viewControllers lastObject];<br /> if ([currentController class] == [MapViewController class])<br /> [currentController performSelectorOnMainThread:@selector(showAnnotations:) withObject:nil waitUntilDone:NO];<br />}<br /></PRE><br /><br />I'd like to do this in Android, too...but a) their map implementation works a lot slower, b) I don't think there even <i>is</i> a method to get the currently active Activity.<br /><br />Now, the "showAnnotations:" method within MapViewController is obviously trickier. For one thing, it's synchronized, lest the user try to filter a map just when a background thread is adding listings - not really a UI issue, since this usually takes all of 1-2 seconds:<br /><br /><PRE><br />-(void)doShowAnnotations:(NSArray*)annotationsToShow {<br /> //autorelease pool<br /> NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];<br /> <br /> @synchronized (self) {<br /> @try {<br /> NSArray *wikiPageMarkers = [WikiPage getPageMarkersWithin:mapView.region];<br /> <br /> BOOL added=NO;<br /> double pageLevel = [Settings getMapPageLevel];<br /> BOOL abovePageLevel = mapView.region.span.longitudeDelta > pageLevel || mapView.region.span.latitudeDelta > pageLevel;<br /><br /> if (abovePageLevel && [mapView.annotations count] > [wikiPageMarkers count]) { //clear away low-level annotations<br /> [mapView performSelectorOnMainThread:@selector(removeAnnotations:) withObject:[annotations allObjects] waitUntilDone:YES];<br /> [annotations removeAllObjects];<br /> }<br /> else if (!abovePageLevel)<br /> {<br /> UITabBarItem *selected = [self.tabBar selectedItem];<br /> if (selected!=nil) {<br /> //first, remove all annotations that don't fit the selection<br /> NSMutableArray *toRemove = [NSMutableArray arrayWithCapacity:[mapView.annotations count]];<br /> for (NSObject *annotation in mapView.annotations) {<br /> if ([annotation class] == [Listing class]) {<br /> Listing *listing = (Listing*) annotation;<br /> if (!(selected.tag==MY && [listing isInMyListings] || selected.tag==[listing.category intValue]))<br /> [toRemove addObject:listing];<br /> }<br /> }<br /> [mapView performSelectorOnMainThread:@selector(removeAnnotations:) withObject:toRemove waitUntilDone:YES];<br /> }<br /> <br /> if (annotationsToShow==nil) { //if we don't have a specific request, get all the listings within the map's region<br /> NSNumber *category = selected==nil ? nil : [NSNumber numberWithInt:selected.tag];<br /> annotationsToShow = [ListingManager getListingsWithin:mapView.region forCategory:category];<br /> }<br /><br /> //the following is incredibly messy because NSSet and NSMutableSet are unusable for our purposes.<br /></PRE><br /><br />What follows is one of the reasons I hate the SDK. Basically, I want to do some fairly basic set arithmetic to ensure that we remove undesired annotations from the map (but keep them in our local "annotations" set in case we need to add them again) and add new ones that are desired. Because the "-unionSet:" etc. methods on NSMutableSet don't work at all like you'd expect, though, I basically have to do that by hand. I'll skip over that messy part to the good stuff:<br /><br /><PRE><br /> NSMutableArray *thereNotRequested = [NSMutableArray arrayWithArray:mapView.annotations];<br /> for (annotation in mapView.annotations) {<br /> if ([requested objectForKey:[annotation title]] != nil)<br /> [thereNotRequested removeObject:annotation];<br /> }<br /><br /> [mapView performSelectorOnMainThread:@selector(removeAnnotations:) withObject:thereNotRequested waitUntilDone:YES];<br /><br /> if ([arrayToAdd count]>0) {<br /> [mapView performSelectorOnMainThread:@selector(addAnnotations:) withObject:arrayToAdd waitUntilDone:YES];<br /> added=YES;<br /> }<br /><br /> if (!added)<br /> [self performSelectorOnMainThread:@selector(activityDone) withObject:nil waitUntilDone:NO];<br /> }<br /> @catch(NSException *exception) {<br /> [Util doLog:[NSString stringWithFormat:@"Warning: adding annotations to map view failed: %@", [exception reason]]];<br /> [self performSelectorOnMainThread:@selector(activityDone) withObject:nil waitUntilDone:NO];<br /> }<br /> @finally {<br /> [pool release];<br /> }<br /> }<br /></PRE>Jonhttp://www.blogger.com/profile/17475458068193351080noreply@blogger.com2tag:blogger.com,1999:blog-259176237881102296.post-73334317387950672162010-04-06T19:28:00.000-07:002010-04-06T19:58:59.220-07:00SQLite on AndroidSo a <a href="http://www.cyrket.com/p/android/com.rezendi.itravel/">commenter</a> on Android Market suggested I allow users store my app data on their SD card rather than phone memory. Great idea, I thought, and promptly went Googling to look for some example code. Alas, there wasn't any. So I wrote my own; and here it is for those who find themselves in a similar situation.<br /><br />The basic Android model is for all Activity classes to have an associated DBHelper class. I don't like this at all; you waste all kinds of time writing and instantiating and opening and closing your DBHelpers, for the sake of (in my app) maybe twenty different database calls. So instead I went and created a singleton DB object. Here's the static code:<br /><br /><PRE><br />public class DB {<br /> private static DB instance;<br /> SQLiteDatabase mDB;<br /> DatabaseHelper mDbHelper;<br /> final Context mCtx;<br /><br /> public static DB GetFor(Context context) {<br /> if (instance==null)<br /> instance = new DB(context);<br /> if (!instance.isOpen())<br /> instance.open();<br /> return instance;<br /> }<br /> <br /> public static void Close() {<br /> if (instance!=null && instance.isOpen())<br /> instance.close();<br /> instance=null;<br /> }<br /><br /> /**<br /> * Database creation sql statement<br /> */<br /> static final String MESSAGE_CREATE =<br /> "create table Message (_id integer primary key autoincrement, "<br /> + "content text not null, dateCreated datetime not null, dateViewed datetime, "<br /> + "messageTitle text, messageType integer, sender text, recipient text); ";<br /><br />// [...other table definitions go here...]<br /><br /> static final String DATABASE_NAME = "iTravel";<br /> static final int DATABASE_VERSION = 1;<br /></PRE><br /><br />(I call DB.Close() in the onDestroy() method of the app's Activities. Now, if you had multiple threads writing to the database simultaneously, this approach would probably get pretty messy in a hurry; fortunately, I don't.)<br /><br />The Android SDK also includes a SQLiteOpenHelper object, which basically takes a Context object and returns a writeable database. I was a little irritated by the need to pass in a Context - it means you have a Context on hand to access the database at all - but presumed it was just necessary for some mysterious reason.<br /><br />Not so mysterious at all. The bad news is, if you want your database to live on your phone's SD card, you can't use the SQLiteOpenHelper. The good news is, it's easy to write an SD-card-compatible variant, one that doesn't require any Context at all:<br /><br /><PRE><br /> static class DatabaseHelper{<br /> private SQLiteDatabase db;<br /> private Context mCtx;<br /><br /> private DatabaseHelper(Context context) {<br /> mCtx=context;<br /> }<br /><br /> public void open() {<br /> File dbDir=null, dbFile=null;<br /> if (Settings.DoSDDB() && Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {<br /> dbDir = Environment.getExternalStorageDirectory();<br /> dbFile = new File(dbDir, "iTravel.sqlite");<br /> }<br /> else<br /> dbFile = mCtx.getDatabasePath("iTravel");<br /><br /> if (dbFile.exists()) {<br /> Log.i("SQLiteHelper", "Opening database at "+dbFile);<br /> db = SQLiteDatabase.openOrCreateDatabase(dbFile, null);<br /> if (DATABASE_VERSION > db.getVersion())<br /> upgrade();<br /> }<br /> else {<br /> Log.i("SQLiteHelper", "Creating database at "+dbFile);<br /> db = SQLiteDatabase.openOrCreateDatabase(dbFile, null);<br /> create();<br /> } <br /> }<br /> <br /> public void close() {<br /> db.close();<br /> }<br /><br /> public void create() {<br /> Log.w(""+this, "Creating Database "+db.getPath());<br /> db.execSQL(MESSAGE_CREATE);<br />// ...other tables go here<br /> db.setVersion(DATABASE_VERSION);<br /> }<br /><br /> public void upgrade() {<br /> Log.w(""+this, "Upgrading database "+db.getPath() +" from version " + db.getVersion() + " to "<br /> + DATABASE_VERSION + ", which will destroy all old data");<br /> db.execSQL("DROP TABLE IF EXISTS Message");<br />// ...other tables go here<br /> create();<br /> }<br /><br /> public SQLiteDatabase getWritableDatabase() {<br /> if (db==null)<br /> open();<br /> return db;<br /> }<br /></PRE><br /><br />Turns out the only thing we ever needed that Context for was its "getDatabasePath()" method, as that varies by application; but if you're using the SD card, you don't need that at all. (The above implementation supports both SD-card and phone-memory databases. Just in case.)<br /><br />So what happens in the DB object's instance(s)? Easy enough -<br /><PRE><br /> public DB(Context ctx) {<br /> this.mCtx = ctx; <br /> }<br /><br /> public DB open() throws SQLException {<br /> if (mDbHelper==null)<br /> mDbHelper = new DatabaseHelper(mCtx);<br /> if (mDB==null || !mDB.isOpen())<br /> mDB = mDbHelper.getWritableDatabase();<br /> return this;<br /> }<br /><br /> public void close() {<br /> mDbHelper.close();<br /> }<br /><br /> public boolean isOpen() {<br /> return mDB!=null && mDB.isOpen();<br /> }<br /><br /> public boolean deleteAll() {<br /> mDB.delete("Message", null, null);<br />// ...other tables go here<br /> return true;<br /> }<br /><br /> public Message[] fetchMessages(String where, String[] args) throws SQLException {<br /> Cursor cursor = mDB.query(true, "Message",<br /> new String[] {"_id", "messageTitle", "content" },<br /> where, args, null, null, "dateCreated desc", null);<br /><br /> Message[] messages = new Message[cursor.getCount()];<br /> cursor.moveToFirst();<br /> int i=0;<br /> while (!cursor.isAfterLast()) {<br /> messages[i++] = new Message(cursor.getString(1), cursor.getString(2));<br /> cursor.moveToNext();<br /> }<br /> cursor.close();<br /> return messages;<br /> }<br /> <br /> public void saveMessage(Message message) {<br /> ContentValues values = new ContentValues();<br /> values.put("messageTitle", message.getTitle());<br /> values.put("content", message.getData());<br /> values.put("messageType", message.getMessageType());<br /> values.put("dateCreated", System.currentTimeMillis());<br /> mDB.insert("Message", null, values);<br /> }<br /></PRE><br /><br />et voila: all your database access in one place, accessed by a simple DB.GetFor(Context context) call from anywhere in your app (and you don't even need the Context if you know the DB will live on the SD card!) and nicely abstracting out the crazy ten-positional-arguments-in-a-row "query" method on SQLiteDatabase.Jonhttp://www.blogger.com/profile/17475458068193351080noreply@blogger.com7tag:blogger.com,1999:blog-259176237881102296.post-56505294199281306152010-03-01T19:02:00.000-08:002010-03-01T19:15:42.000-08:00Responding to zooms and pans in Android's MapViewThere's a curious lacuna in Android's MapView API: it's (relatively) easy to display a map, and overlay items atop a map; it's (relatively) easy to detect when an overlay item has been touched; but there's no straightforward way to work out when the user has touched anywhere else on the map. Because of the way MapView works, the usual onTouchListener() solution only works for one touch, and then fails.<br /><br />There is, however, a solution. Not a pretty one, but it works. The solution is to use your own subclass of MapView:<br /><br /><PRE><br />public class ITRMapView extends MapView {<br /> public ITRMapView(android.content.Context context, android.util.AttributeSet attrs) {<br /> super(context, attrs);<br /> }<br /><br /> public ITRMapView(android.content.Context context, android.util.AttributeSet attrs, int defStyle) {<br /> super(context, attrs, defStyle);<br /> }<br /><br /> public ITRMapView(android.content.Context context, java.lang.String apiKey) {<br /> super(context, apiKey);<br /> }<br />}<br /></PRE><br /><br />and within that subclass, override onTouchEvent. You're probably only interested in the UP action:<br /><PRE><br /> public boolean onTouchEvent(MotionEvent ev) {<br /> if (ev.getAction()==MotionEvent.ACTION_UP) {<br /> //do your thing<br /> }<br /> return super.onTouchEvent(ev);<br /> }<br /></PRE><br /><br />But what if you want to detect <i>zoom</i> actions as well as touches? Simple, thought I: just override onDraw() and do the same thing. But you can't - MapView's onDraw() is <b>final</b>!<br /><br />Catastrophe? Not quite. It turns out that overriding dispatchDraw() works just fine:<br /><PRE><br /> int oldZoomLevel=-1;<br /><br /> public void dispatchDraw(Canvas canvas) {<br /> super.dispatchDraw(canvas);<br /> if (getZoomLevel() != oldZoomLevel) {<br /> //do your thing<br /> oldZoomLevel = getZoomLevel();<br /> }<br /> }<br /></PRE><br /><br />Et voila - you can programmatically detect and respond when the user pans and/or zooms your map. Really not so hard after all.Jonhttp://www.blogger.com/profile/17475458068193351080noreply@blogger.com17tag:blogger.com,1999:blog-259176237881102296.post-56810590399033543152010-02-08T12:12:00.000-08:002010-02-08T12:16:15.571-08:00Android vs. iPhone: A Developer's Perspective, part II<center><b><i>Android vs. iPhone: A Programmer's Perspective - II</i></b></center><br /><br />(See also <a href="http://www.rezendi.com/pa/2010/02/android-vs-iphone-developers.html">Part I</a>.)<br /><br /><br /><b>OS features</b><br /><br />The big winner here is Android, due to its multitasking. You can call other apps, eg a browser or a file-system picker, get results from them, and use those results in your own app; all these things are completely impossible on the iPhone, where (aside from a few special cases like iTunes) only one app may run at a time. (And even if you want to sacrifice yourself to launch another app, you can only do so in very restricted circumstances - if they have registered a URL scheme.)<br /><br />The browser special-case is worth mentioning; you can include browser windows in your own app, and mine do so in a few different places - but this is often not as full-featured or convenient to the user as opening up the full Safari browser.<br /><br />You can also write Android services that run in the background, and you can launch them at boot time (if the user permits) by registering for the BOOT_COMPLETED intent. What it doesn't really, provide, though, is "push" notifications (other than by faking it with eg Comet HTTP Push) which the iPhone does offer. That's the iPhone's only advantage in this category, though.<br /><br /><br /><b>Phone features</b><br /><br />The iPhone is locked down. You don't get direct Bluetooth API access; you do in Android. You don't get direct SMS access; you do in Android. For security reasons, they claim in Cupertino. At least (like Android) it now lets you access the proximity sensor.<br /><br />But to its credit, the features it does offer are a joy to work with. In particular, the built-in camera/preview screen (for iPhone) / picture selector (for iPod Touch) is excellent, and requires all of a half-dozen lines of code to launch and respond to. The Android camera code, last I looked at it, was much more complex.<br /><br />Location management is a little messy and complex on both systems, but overall Android's registration model is easier to work with than the iPhone's delegation model.<br /><br />The iPhone SDK comes with this daft notion that all settings for all apps should probably be in a single System Settings screen accessible from the main menu; you can roll your own, but it's inconvenient. Android, by contrast, lets you create a settings screen by simply writing XML, no Java required unless you want to customize it. On the other hand, the iPhone simply makes "your default settings" available, whereas Android provides the possibility of multiple sets, which is doubtless more flexible and powerful but also more annoying to work with.<br /><br />Accessing system and app resources (eg image files) is a little counterintuitive on Android; at compile time, it scans a predetermined bunch of directories, and automatically builds an "R" file with a bunch of final static ints, each of which uniquely identifies a resource; you then use those in code to access resources. (There's also an Android.R for built-in-resources.) This is confusing at first, but fine once you get used to it.<br /><br />The iPhone makes the basics easy for you in code - <PRE>[Image imageNamed:@"myImage.png"]</PRE> - but if you want to go beyond that, the whole resource-bundling thing is less than intuitive, and while I had no trouble accessing bundle resources, I never felt like I had a clear idea of what was actually going on, unlike with Android.<br /><br /><br /><b>Screen building</b><br /><br />No sense pussyfooting around: when it comes to actually building the screens of your app, the iPhone has a massive advantage. It provides an excellent WYSIWYG tool, and the components it offers - buttons, lists, etc - mostly just look a whole lot nicer and sexier than the Android ones.<br /><br />(That said, I have two minor complaints about the iPhone UI components: 1) No drop-down options in menus - instead you either have to code an ActionView or use one of the huge screen-eating spinners. 2) The absence of a border around TextViews does not look good and just serves to confuse users.)<br /><br />In general, though, the iPhone wins here. The delegate model of TableViewController gives you powerful and fine-grained control far more easily than the adapter model of ListActivity. As far as "complicated, hard-to-work-with, but useful subclasses of your basic list view" goes, I'll take the iPhone's LocalizedIndexedCollation over Android's ExpandableListView, though I sure wish both were more developer-friendly.<br /><br />And then there's maps. Jeez. In iPhone, if you want to add a custom marker for a map, then in the ViewController for that screen, you just override a method and write six lines of code:<br /><PRE><br />- (MKAnnotationView *)mapView:(MKMapView *)myMapView viewForAnnotation:(id <MKAnnotation>)annotation {<br /> NSString viewImageName=@"myImage.jpg";<br /> MKAnnotationView *myView = (MKAnnotationView*)[myMapView dequeueReusableAnnotationViewWithIdentifier:viewImageName];<br /> if (myView==nil) {<br /> myView = [[[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:viewImageName] autorelease];<br /> myView.image = [UIImage imageNamed:viewImageName];<br /> }<br /> return myView;<br />}<br /></PRE><br /><br />In Android, first you have to write a whole new inner class that extends ItemizedOverlay<OverlayItem>, eg:<br /><PRE><br /> class ListingsOverlay extends ItemizedOverlay<OverlayItem> {<br /> private ArrayList<OverlayItem> overlays=new ArrayList<OverlayItem>();<br /><br /> public ListingsOverlay(android.graphics.drawable.Drawable defaultMarker) {<br /> super(defaultMarker);<br /> }<br /><br /> public void addOverlay(OverlayItem overlay, Drawable marker) {<br /> super.boundCenterBottom(marker);<br /> overlay.setMarker(marker);<br /> overlays.add(overlay);<br /> }<br /><br /> // necessary because populate() is protected<br /> public void doPopulate() {<br /> populate();<br /> }<br /><br /> @Override<br /> protected OverlayItem createItem(int i) {<br /> return(overlays.get(i));<br /> }<br /><br /> @Override<br /> public int size() {<br /> return(overlays.size());<br /> }<br /></PRE><br /><br />and then something like this:<br /><br /><PRE><br /> mapView = (MapView) findViewById(R.id.mapview);<br /> mapOverlays = mapView.getOverlays();<br /> mapOverlays.removeAll(mapOverlays);<br /><br /> Drawable drawable = getResources().getDrawable(R.drawable.map_fave);<br /> itemizedOverlay = new ListingsOverlay(drawable);<br /> OverlayItem overlay = new OverlayItem(point, mappable.getIDString(), mappable.getMapDetailText());<br /> Drawable marker = MappableItem.GetMarkerForMappable(ITRMapView.this, mappable.getCategory());<br /> itemizedOverlay.addOverlay(overlay, marker);<br /> itemizedOverlay.doPopulate();<br /></PRE><br /><br />Menus and navigation are also easier and prettier on the iPhone; you can add sleek-looking buttons and toolbars and simply set them to call the selector of your choice, and you get a great NavigationController for iTunes-like interfaces, plus sexy animation. No real equivalent on Android.<br /><br />On the other hand, Android's XML layouts, while tedious and irritating, and not as pretty or near as exact as the iPhone's WYSIWYG, do work well once you get the hang of them - and they make it much easier to support multiple screen sizes and different orientations. (My iPhone app simply doesn't do landscape orientation; my Android app handles it almost perfectly, without me ever having thought about it.) This wasn't a big deal for the iPhone until last month - but apps that previously were confident of a 320x480 screen now have to deal with the iPad.<br /><br /><br /><b>The Internet</b><br /><br />Accessing web services and launching in-app web views is easy and effective in both Android and iPhone. Edge to the latter, though; there are a couple of weird little bugs with Android's WebViews (though they can be worked around with ease) and the iPhone gives you both more SDK options and better documentation.<br /><br /><br /><b>Release</b><br /><br />Building an iPhone app is kind of scary. You're suddenly reminded that under the hood it's terrifying C++; the "Build" screens are full of dozens if not hundreds of byzantine, cryptic, intimidating options for compiling, precompiling, linking, etc., and you find yourself desperately hoping you've set up your import libraries perfectly and suddenly very careful not to touch anything.<br /><br />That said, XCode works really well. (Have I mentioned that debugging is far easier with the iPhone SDK? Debugging is far easier with the iPhone SDK. With Android I usually wind up resorting to debugging with log messages.) What does not work really well is Apple's paranoid certification hegemony. God forbid that anyone run an app without going through the App Store!<br /><br />So you need to go to Apple's site and futz around with it and with device IDs and create and download separate certificates for debug and release, and your temporary "provisioning" device certificates expire every three months, and while it is theoretically possible to build an app for someone else's device, email it to them, and have them install it, I have yet to actually succeed at this, despite repeated attempts. (It's somewhat easier if their device is plugged in to your machine.)<br /><br />You know how it works on Android?<br />- You build your app.<br />- You sign your app. (Which Eclipse can take care of with a simple wizard.)<br />- Anyone in the whole world who wants to can now download and run the app.<br /><br />There's a slight pitfall if you're working with Google Maps - you have to jump through hoops like Apple's to create separate debug and release Maps API Keys, and ensure you're using the right one - but by and large, it's miles easier and better than trying to finagle your way into Apple's walled garden.<br /><br />Plus, if you've built an app and released it, and found some sort of subtle bug? With Android, you can fix that and have a new version up on the Android Market in five minutes. With Apple, it's ... a week? A month? Who knows? App Store approval is an infuriating black box.<br /><br /><br /><b>Overall</b><br /><br />They're both excellent systems. They both have their pros and cons. Overall I would rate the iPhone as better, both in terms of what you can do with it and how - but Android is superior in fundamental ways (eg multitasking and memory management) and catching up fast in terms of results. If Apple doesn't watch out, and move fast, they're going to find themselves superseded soon. Maybe this year.Jonhttp://www.blogger.com/profile/17475458068193351080noreply@blogger.com7tag:blogger.com,1999:blog-259176237881102296.post-73236520747444027912010-02-07T20:30:00.001-08:002010-02-08T19:49:47.110-08:00Android vs. iPhone: A Developer's Perspective, part I<center><b><i>Android vs. iPhone: A Programmer's Perspective</i></b></center><br /><br />(See also <a href="http://www.rezendi.com/pa/2010/02/android-vs-iphone-developers_08.html">Part II</a>.)<br /><br />I've spent the last month or so building both Android and iPhone versions of my app <b>iTravel</b>. (See <a href="http://wetravelright.com/">http://wetravelright.com/</a> for details and links.) Which gives me a pretty good perspective from which to compare and contrast the Android and iPhone environments and SDKs. Hence I give you the following head-to-head analysis, from a developer's point of view:<br /><br /><br /><b>Language</b><br /><br />Non-programmers often think that one's language of choice is a big deal, but really, once you've learned two or three programming languages, picking up another is generally something you can do in a day or two. That said, there are often substantive differences. And this is definitely true of Java (for Android) and Objective-C (for iPhone.)<br /><br />Let's start off with the really annoying stuff: Objective-C's memory management. By which I mean, its complete lack of any. Programmers have to manually allocate and release memory when writing for the iPhone SDK, which is positively medieval. If you fail to do so, and there are many pitfalls, then you leak memory which is lost until the device reboots. This is awful. (And it's no longer true of the Mac SDK, incidentally; but the iPhone is behind the times.)<br /><br />There are other annoyances. You have two files to contend with for every class - a .h and a .c file. Which is inconvenient and complicating and inelegant. And suppose you have a basic, bog-standard instance variable. You generally wind up declaring it in, count 'em, not one, not two, not three, but four different places.<br /><br />In your .h:<br /><PRE><br />{<br /> NSObject *object<br />}<br /><br />@property (nonatomic, retain) NSObject *object<br /></PRE><br /><br />In your .c;<br /><PRE><br />@synthesize object<br /></PRE><br />and later, in dealloc(),<br /><PRE><br />[object release];<br /></PRE><br />Whereas with Java, you have one single .java file, which in general will have<br /><PRE><br />private Object object;<br />public Object getObject() { return object; }<br />private void setObject(Object o) { object=o; }<br /></PRE><br />all in one place. I know which one I think is easier.<br /><br />But. On the other hand. Objective-C is sort of the bastard son of C, which is awful, and Smalltalk, which is awesome. As a result, it has Smalltalk-like features like selectors:<br /><PRE><br />[caller performSelector:@selector(myFunctionName)]<br /></PRE><br />...in short, you can use functions as (more or less, ish) first-class objects. Try that in Java and if memory serves you'll most likely wind up in the irritating labyrinth of reflection. Plus, you get options like "doesNotRecognizeSelector:", which can be easily misused, but is potentially very powerful, and does not exist in Java.<br /><br />On the other hand, Objective C is really annoyingly logorrheic (meaning wordy) especially when it comes to string handlers. Suppose you have strings A and B, and you wish to combine them into string C. In Java, the syntax is<br /><PRE><br />C=A+B;<br /></PRE><br />whereas in Objective-C, you type<br /><PRE><br />C = [A stringByAppendingString: B]<br /></PRE><br />Or suppose you want the location of the last slash in string A. Java:<br /><PRE><br />n=A.lastIndexOf("/");<br /></PRE><br />Objective-C:<br /><PRE><br />n = [A range ofString:@"/" options:NSBackwardSearch].location;<br /></PRE><br />I much prefer Java's syntax and simplicity. But I do admire Objective-C's flexibility.<br /><br /><br /><b>Development environment</b><br /><br />By this I mean: the "integrated development environment" in which coders work; the documentation for the IDE, the language, and the libraries; the testing and source-code support; and all the stuff that is meant to help you write better code faster.<br /><br />The Android and iPhone IDEs and documentation really incarnate the attitudes of the two companies in question. Android doesn't exactly have an IDE of its own, although they recommend that you use the Android plug-in for the open-source Eclipse IDE, which is slow, irritating, and buggy in various minor ways. The documentation is written by smart people for smart people, with little handholding. Flashy graphics are minimal to nonexistent. And a lot of important stuff is still handled by tools meant to be run from a shell rather than a GUI. But the search function is excellent.<br /><br />Apple's IDE is slick, seamless and powerful. It comes with a visual tool to help you lay out the screens of your app. The documentation is full of step-by-step guides (although they are often oddly lacking or confusing) and high-quality graphics and other visualizations.<br /><br />I have many complaints about both. Eclipse is slow and annoying, and I could only get Android's JUnit test harness to run successfully from a terminal window, rather than the IDE; similarly, I had to use shell tools to sign packages, get a fingerprint for a Maps IDE, install a package on my phone, etc. All of which really calls into question the I in IDE.<br /><br />On the other hand, at last the external unit-testing actually works; XCode's built-in harness is so bad that Google built and released an entirely separate one, which has the advantage of actually functioning correctly. On the other hand, its Subversion integration is excellent, which is not true of Eclipse.<br /><br />Both have plenty of official and unofficial online support, as well, at official support sites and places like Stack Overflow. Android's open-source ethos gives it a big advantage in terms of external packages, though; for instance, if you want to build a barcode scanner into an Android app, there's a whole open-source library out there for you, ready to be plugged in. For the iPhone? You'll have to roll your own. Sorry.<br /><br /><br /><b>Multithreading</b><br /><br />In phone apps multithreading is key, because the phone needs to remain as responsive as possible, so you need to do your heavy lifting behind the scenes, outside the main UI thread.<br /><br />Both the iPhone SDK and Android support multithreading, but the latter's is much more convenient, especially if you want to call back to the main thread once your background thread has done its thing. On the iPhone, you have to do something like:<br /><PRE><br />-(void) doWebView {<br /> NSThread* htmlThread = [[NSThread alloc] initWithTarget:self selector:@selector(loadHtml) object:nil];<br /> [htmlThread start];<br /> [htmlThread release];<br />}<br /><br />-(void) loadHtml {<br /> NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];<br /> NSString *html = doUnroll ? [self getUnrolledData] : root.data;<br /> html=[NSString stringWithFormat: @"%@%@</body></html>", [Util getBaseHtml], html];<br /> [self performSelectorOnMainThread:@selector(setHtml:) withObject:html waitUntilDone:NO];<br /> [pool release];<br />}<br /><br />-(void) setHtml:(NSString*)html {<br /> [webView loadHTMLString:html baseURL:nil];<br /> [webView sizeToFit];<br /> [self.tableView setTableHeaderView:webView];<br />}<br /></PRE><br />Whereas on Android, you can use Java's equally irritating Runnable() framework, but Android provides an extremely convenient (and quite flexible) short form. Just subclass AsyncTask in an inner class:<br /><PRE><br /> new LoadHtmlTask().execute();<br /><br /> class LoadHtmlTask extends AsyncTask<String, Integer, String> {<br /> protected String doInBackground(String... strings) {<br /> String headerData = Settings.GetHtmlPrefix() + (unrolled ? getUnrolledData(viewRoot) : viewRoot.getData());<br /> return headerData;<br /> } <br /><br /> protected void onPostExecute(String results) {<br /> mHeaderView.loadDataWithBaseURL("local", headerData, "text/html", "utf-8", "");<br /> }<br /> }<br /></PRE><br />which seems much more encapsulated and intuitive to me.<br /><br /><br /><b>Persistence</b><br /><br />On paper, the iPhone environment has a big advantage here: it features the Core Data object-persistence layer above the SQLite database, whereas Android requires direct DB access.<br /><br />For me, though, direct DB access was not awful, and given the constraints of my app, arguably simpler than jumping through all of Core Data's hoops - using the separate tool to declare a data model, having to rebuild your custom code every time you add a column, etc. All that without even getting thread safety.<br /><br />However, I'm totally comfortable writing SQL, not all developers are, and my app had pretty straightforward DB requirements. Core Data is undeniably more elegant and ultimately better. Plus you get nifty little features like shake-to-undo, semi-automatic migration data models in installed apps, etc. And it's not like the Android tools are particularly easy to work with. Check out the method in android.database.sqlite.SQLiteDatabase you use to perform a query:<br /><PRE><br />public Cursor query (boolean distinct, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit)<br /></PRE><br />As a (Google employee) friend of mine said, "Holy positional parameters, Batman!" Needless to say, one quickly wraps this monstrosity in other methods less prone to grievous error...<br /><br /><br /><a href="http://www.rezendi.com/pa/2010/02/android-vs-iphone-developers_08.html">Part II</a> of this post compares and contrasts system features, phone features, settings and resources, screen building, internet connectivity, and the app install/release process. (It does not compare and contrast graphics programming, as my apps are data-heavy not graphics-heavy.) Don't touch that dial.Jonhttp://www.blogger.com/profile/17475458068193351080noreply@blogger.com6tag:blogger.com,1999:blog-259176237881102296.post-17150430055520853422010-01-31T16:09:00.000-08:002010-01-31T16:31:22.475-08:00Back in the Android saddleSo now that versions 2.0 of my iPhone app are <a href="http://wetravelright.com/">up and running on the App Store</a>, I've finally started writing an Android version. You may recall that this blog was supposed to be primarily about Android development from the get-go. We apologize for the eight-month sidetrack.<br /><br />Anyway, It's been going quite well. Both the Android and iPhone SDK have their pros and cons. I like XCode better than Eclipse, and I generally (though not always) prefer Core Data to direct DB queries; on the other hand, string processing is far easier in Java, Android's multithreading is easier to work with, I vastly prefer single .java files vs twinned .h/.c files, and I love not having to worry about manual memory management.<br /><br />The Android version is now mostly functionally complete. Things I have (sometimes re) learned which may be of interest:<br /><br /><UL><br /><LI>Both the Android and iPhone OSes restrict background threads from directly calling the user interface. With the iPhone, you need to use "performSelectorOnMainThread:"; with Android, you need to use "postInvalidate()" rather than "invalidate()" to get a View to redraw itself.<br /><LI>I'm experimenting with a database-access model wherein all my Activities do the following:<br /><PRE><br /> protected DB db;<br /><br /> @Override<br /> protected void onCreate(Bundle savedInstanceState) {<br /> super.onCreate(savedInstanceState);<br /> db = new DB(this);<br /> db.open();<br /> }<br /><br /> @Override<br /> protected void onResume() {<br /> super.onResume();<br /> db.open();<br /> }<br /> <br /> @Override<br /> protected void onPause() {<br /> super.onPause();<br /> db.close(); <br /> }<br /></PRE><br /><br />wherein DB encapsulates the database, and all database calls go through it. This is a variant of the "DbHelper" model that you see in the Android tutorials, and imho and simpler and better one in most circumstances. It's mostly implemented as per the above in abstract superclasses of the instantiated activities.<br /><br />You then have accessor methods such as<br /><PRE><br /> db.saveListing(listing);<br /></PRE><br />which is handled pretty much as per the tutorials, and<br /><PRE><br /> Listing[] listings = db.fetchListingsForPage(Util.SQLize(pageURL));<br /></PRE><br />which calls<br /><PRE><br /> public Listing[] fetchListingsForPage(String pageURL) throws SQLException {<br /> return fetchListingsFor("pageURL LIKE '"+pageURL+"%'", (String[])null);<br /> }<br /></PRE><br />which in turn calls the generic<br /><PRE><br /> public Listing[] fetchListingsFor(String where, String... args) throws SQLException {<br /> Cursor cursor = mDB.query(true, "Listing",<br /> new String[] {"_id", "name", "data", "isFlagged", "category", "address", "url",<br /> "pageURL", "sectionName", "sectionNumber", "location", "downloadDate" },<br /> where, args, null, null, null, null);<br /><br /> Listing[] listings = new Listing[cursor.getCount()];<br /> cursor.moveToFirst();<br /> int i=0;<br /> while (!cursor.isAfterLast()) {<br /> listings[i++] = new Listing(cursor.getLong(0), cursor.getString(1), cursor.getString(2), cursor.getInt(3),<br /> cursor.getInt(4), cursor.getString(5), cursor.getString(6), cursor.getString(7), cursor.getString(8),<br /> cursor.getString(8), cursor.getString(10), cursor.getLong(11));<br /> cursor.moveToNext();<br /> }<br /> cursor.close();<br /> return listings;<br /> }<br /></PRE><br />which is in course incredibly ugly, but at least it only happens in one place.<br /><br /><LI>Here's an Activity that serves as a browser within your app, in its entirety.<br />Layout:<br /><PRE><br /><?xml version="1.0" encoding="utf-8"?><br /><WebView android:id="@+id/web" xmlns:android="http://schemas.android.com/apk/res/android"<br /> android:layout_width="fill_parent"<br /> android:layout_height="fill_parent"/><br /></PRE><br />Code:<br /><PRE><br />public class WebDisplay extends ITRActivity {<br /> public static String KEY_URL = "url";<br /> public static String KEY_DATA = "data";<br /> <br /> String mUrl;<br /> String mData;<br /> <br /> @Override<br /> public void onCreate(Bundle savedInstanceState) {<br /> super.onCreate(savedInstanceState);<br /> setContentView(R.layout.web);<br /> WebView web = (WebView) findViewById(R.id.web);<br /><br /> Bundle extras = getIntent().getExtras();<br /> mUrl = extras == null ? null : extras.getString(KEY_URL);<br /> mData = extras == null ? null : extras.getString(KEY_DATA);<br /> <br /> if (mUrl!=null)<br /> web.loadUrl(mUrl);<br /> else if (mData!=null)<br /> web.loadData(mData.replace("%","%"), "text/html", "utf-8"); <br /> } <br />}<br /></PRE><br /></UL><br /><br />More to come when I release v1.0, which should happen in the next ten days.Jonhttp://www.blogger.com/profile/17475458068193351080noreply@blogger.com4tag:blogger.com,1999:blog-259176237881102296.post-86796712882232854292010-01-18T18:24:00.001-08:002010-01-31T16:29:48.214-08:00Using Core Data in a multithreaded environment.You have to do a lot of iPhone stuff in background threads, to maintain a snappily responsive user interface. But if you're using Core Data, well - to quote <a href="http://developer.apple.com/Mac/library/documentation/Cocoa/Conceptual/CoreData/Articles/cdMultiThreading.html">the docs</a>:<br /><br /><i>Managed objects are not thread safe [...] Core Data does not present a situation where reads are "safe" but changes are "dangerous"—every operation is "dangerous" because every operation can trigger faulting.</i><br /><br />Sound intimidating? No worries: it's a piece of cake. Just wrap the code where you get your ManagedObjectContext in a method something like this:<br /><br /><PRE><br />@implementation Util<br /><br />+(NSManagedObjectContext*)getManagedObjectContext {<br /> UIApplication *app = [UIApplication sharedApplication];<br /> MyAppDelegate *appDelegate = app.delegate;<br /> if ([NSThread isMainThread])<br /> return [appDelegate managedObjectContext];<br /> else<br /> return [appDelegate getMOCFor:[NSThread currentThread]];<br />}<br /></PRE><br /><br />and add the following method to your application delegate:<br />(where "threadMOCs", obviously, is a properly defined and synthesized ivar.)<br /><br /><PRE><br />- (NSManagedObjectContext*) getMOCFor:(NSThread*) thread {<br /> if (!threadMOCs)<br /> self.threadMOCs=[NSMutableDictionary dictionaryWithCapacity:16];<br /> <br /> NSNumber *threadHash = [NSNumber numberWithInt:[thread hash]];<br /> if ([threadMOCs objectForKey:threadHash]==nil) {<br /> NSManagedObjectContext *newMOC = [[NSManagedObjectContext alloc] init];<br /> NSError *error=nil;<br /> NSURL *storeUrl = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"myDBName.sqlite"]]; <br /> NSManagedObjectModel *model = [self managedObjectModel];<br /> NSPersistentStoreCoordinator* threadPSC = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: model];<br /> if (![threadPSC addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:nil error:&error])<br /> { //handle error here }<br /><br /> [newMOC setPersistentStoreCoordinator: threadPSC];<br /> [threadMOCs setObject:newMOC forKey:threadHash];<br /> }<br /> return [threadMOCs objectForKey:threadHash];<br />}<br /></PRE><br /><br />Et voila! A new object context and persistent store coordinare for every thread, which gives you full concurrent access to your data. (Though you probably still have to be careful about passing managed objects <i>across</i> threads...)Jonhttp://www.blogger.com/profile/17475458068193351080noreply@blogger.com1tag:blogger.com,1999:blog-259176237881102296.post-66759165996108414212009-11-30T14:18:00.001-08:002009-12-16T08:17:38.731-08:00How to store images larger than 1 megabyte in Google App EngineOver the summer, Google App Engine raised its limits for web requests and responses from 1MB to 10MB, but kept the maximum size of any single database element at 1MB. If you try to exceed this, you'll get a MemoryError. You can find a fair amount of grief and woe and gnashing of teeth and wearing of sackcloth and ashes about this online.<br /><br />Which is kind of surprising, because it's not <i>that</i> hard to break files up into chunks and store those chunks in the database separately. Here's what I did today for <a href="news.bbc.co.uk/2/hi/8258501.stm">my current project</a>, which stores data - including photos - uploaded from smartphones:<br /><br />First, we have to receive the uploaded image. Our uploads are two-phase - first data, then a photo - for various reasons. The data upload includes the image's file name; the photo upload is a basic form/multipart POST with exactly one argument (the filename) and its value (the file).<br /><br />So, in "main.py":<br /><PRE><br />class SaveImage(webapp.RequestHandler):<br /> def post(self):<br /> entryHandler=ec.EntryHandler()<br /> for arg in self.request.arguments():<br /> file = self.request.get(arg)<br /> response = entryHandler.saveImage(arg,file)<br /> self.response.out.write(response)<br /></PRE><br /><br />and in "ec.py":<br /><br /><PRE><br />class ImageChunk(db.Model):<br /> entryRef = db.ReferenceProperty(Entry)<br /> chunkIndex = db.IntegerProperty()<br /> chunk = db.BlobProperty()<br /><br />class EntryHandler:<br /> def saveImage(self, fileName, file):<br /> results = Entry.all().filter("photoPath =", fileName).fetch(1)<br /> if len(results)==0:<br /> logging.warning("Error - could not find the entry associated with image name "+fileName)<br /> return "Failed"<br /> else:<br /> MaxBTSize=1000000<br /> entry = results[0]<br /> marker=0<br /> chunks=[]<br /> while marker*MaxBTSize<len(file):<br /> if MaxBTSize*(marker+1)>len(file):<br /> chunk = ImageChunk(entryRef=entry, chunkIndex=marker, chunk=db.Blob(file[MaxBTSize*marker:]))<br /> else:<br /> chunk = ImageChunk(entryRef=entry, chunkIndex=marker, chunk=db.Blob(file[MaxBTSize*marker:MaxBTSize*(marker+1)]))<br /> chunk.put()<br /> marker+=1<br /> logging.info("Successfully received image "+fileName)<br /> return "Successfully received image "+fileName<br /></PRE><br /><br />Pretty basic stuff: we chop the image up at each 1,000,000-byte mark, and put each chunk into its own ImageChunk DB object. <br /><br />Then, when we need to retrieve the image, in 'main.py':<br /><br /><PRE><br />class ShowImageWithKey(webapp.RequestHandler):<br /> def get(self):<br /> key = self.request.get('entryKey')<br /> entryHandler = ec.EntryHandler()<br /> image = entryHandler.getImageByEntryKey(key)<br /> if image is not None:<br /> self.response.headers['Content-Type'] = 'image/jpeg'<br /> self.response.out.write(image)<br /></PRE><br /><br />and in 'ec.py':<br /><br /><PRE><br /> def getImageByEntryKey(self, key):<br /> chunks = db.GqlQuery("SELECT * FROM ImageChunk WHERE entryRef = :1 ORDER BY chunkIndex", key).fetch(100)<br /> if len(chunks)==0:<br /> return None<br /><br /> image=""<br /> for chunkRow in chunks:<br /> image+=chunkRow.chunk<br /> return image<br /></PRE><br /><br />Since db.Blob is a subtype of str, that's all you have to do. I don't understand why some people are so upset about this: it's mildly annoying that I had to write the above, but hardly crippling. At least with JPEGs, which is what we use. (But I don't see why any other file type would be more difficult; they're ultimately all just a bunch of bytes). Could hardly be easier ... well, until App Engine rolls out their <a href="http://code.google.com/appengine/docs/roadmap.html">large file service</a>.<br /><br />(<i>eta, Dec 14:</i> which came out <a href="http://googleappengine.blogspot.com/2009/12/app-engine-sdk-130-released-including.html">today!</a> Meaning you can now disregard all the above and just use the new Blobstore instead.)<br /><br />(<i>eta, Dec 16:</i> mmm, maybe not. Looked at the Blobstore in detail today, and it's really best suited for browser projects, not app or web-service stuff. The API for the blobs is very limited, and you can only access them via one-time-only URLs that App Engine puts in your HTML. You could scrape that, granted, but that's a pain in the ass, no less inelegant than the image-chunking solution above. It's experimental and subject to change, too. I think I'll hold out until its API improves.)Jonhttp://www.blogger.com/profile/17475458068193351080noreply@blogger.com15tag:blogger.com,1999:blog-259176237881102296.post-72962693774701493212009-11-04T08:34:00.000-08:002010-01-31T16:30:10.768-08:00to infinity, and beyond!I am pleased to report that my pet-project iPhone app, <i>iTravelFree</i>, has passed the stern inspection of Apple's App Store and is now available for download worldwide. For app links, a screenshot-laden tutorial, and help and FAQ files, see here: <a href="http://wetravelright.com/">www.wetravelright.com</a>.<br /><br />(Yeah, crappy URL, I know, but all the good ones were taken.)<br /><br />Since this is my tech blog let me wax about its architecture a bit. The iPhone app is pretty straightforward: basically, it's a bunch of TableViewControllers, many of which include WebViews, along with a MapViewController, all pointing to a bunch of CoreData records. Nothing extraordinarily fancy by any means.<br /><br />The server side is more interesting: it's a Google App Engine service, written in Python, that fetches, caches, and parses Wikitravel pages for the app. This gives me a single point of access to the data flow, lets me do things like convert addresses to lat/long location, cuts down on bandwidth for both Wikitravel (thanks to the caching) and the phone app (thanks to the parsing and stripping out of extraneous info.)<br /><br />The general architecture - phone app plus App Engine service - is actually really powerful and easy to work with. Basically, it's a distributed version of the classic Model-View-Controller architecture, where the phone is the view, the App Engine service is the controller, and whatever data you're accessing is the model. This lets you do all the heavy-lifting computation on the server side, which is where it belongs, and keep the phone (and its puny processor) focused almost purely on the UI.<br /><br />I do have some reservations about the BigTable data store that App Engine uses, but they don't apply to projects like this, with relatively simple storage requirements and no data mining. <br /><br />I wrote it in, hrmm, about six weeks all told, starting in July. (Obviously it's been much more than six weeks since then, but I had full-time work starting August so could only work on this in fits and spurts on the side.)<br /><br />Anyway - the app is in pretty good shape, but there's more work to be done on the server side, so it's still basically in beta test. Take a look, download it, play around, and let me know what you think -Jonhttp://www.blogger.com/profile/17475458068193351080noreply@blogger.com7tag:blogger.com,1999:blog-259176237881102296.post-81433548142467295992009-10-14T14:11:00.001-07:002009-10-14T14:28:04.274-07:00jQuery, how do I love thee?So I spent a few days doing some JavaScript, which is not my favourite thing. Or at least it didn't use to be. But now that I have discovered <a href="http://jquery.com/">JQuery</a>, I gotta say, it's a whole lot more tolerable than it used to be.<br /><br />JQuery makes some things that I would previous have considered all but impossible downright easy. Take drag-and-drop inside the browser, f'rinstance. To do it yourself, you'd have to deal with, jeez, I don't even <i>know</i> what, DOM craziness, layers, who knows. In jQuery? Well, lemme give you a quick example, stripped of all the actual business logic, of a drag-and-drop form builder:<br /><br /><PRE><br /><html><head><br /> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script><br /> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.js"></script><br /><br /> <style type="text/css"><br /> .columns:after {<br /> content: ".";<br /> display: block;<br /> height: 0;<br /> clear: both;<br /> visibility: hidden;<br /> }<br /> * html .columns {height: 1%;}<br /> .columns{ display:inline-block; }<br /> .columns{ display:block; }<br /> .columns .column{<br /> float:left;<br /> display:inline;<br /> min-height:360px;<br /> }<br /> .columns .last{ float:right; }<br /> .columns .first{ width:180px; background-color:#ffeeee; }<br /> .columns .second{ width:280px; margin-left:10px; background-color:#eeffee; }<br /> .columns .last{ width:210px; background-color:#eeeeff}<br /><br /> .footers{ display:inline-block; }<br /> .footers{ display:block; }<br /> .footers .footer{<br /> float:left;<br /> display:inline;<br /> }<br /> .footers .last{ float:right; }<br /> .footers .first{ width:180px; background-color:#eeeeee; }<br /> .footers .second{ width:280px; margin-left:10px; background-color:#eeeeee; }<br /> .footers .last{ width:210px; background-color:#eeeeee}<br /><br /> .formLineEdit { text-align: right; }<br /> .optionLabel { float:right; text-align: right; }<br /> .label { font-weight: bold; vertical-align: text-top; }<br /> .formInput { text-align: right; vertical-align: text-top; }<br /> .editHeader { text-align: right; }<br /> .selectOption { text-align: right; }<br /> #error { text-align: center; color: #ff0000; }<br /> #success { text-align: center; color: #00ff00; }<br /> #listForms { float: left; text-align: left; }<br /> #viewHelp { float: right; text-align: right; }<br /> #inputOptions { text-align: right; }<br /> #detailHeader { text-align: right; }<br /> #formName {background-color: #eeeeee; }<br /> #formVersionNumber {background-color: #eeeeee; }<br /> #formSubmitButton {text-align:right; background-color: #eeeeee; }<br /> </style><br /><br /> <script><br /> var totalItems=0;<br /> var currentlyEditing=null;<br /> var lastEdited=null;<br /><br /> $(function() {<br /> //make divs created out of XML clickable<br /> var destClicked=false;<br /> $("#destination").mousedown( function() {<br /> if (!destClicked) { //only do this once, or it might get messy<br /> $("#destination").children().each( function() {<br /> $(this).bind("click", function() {<br /> showEditDetailsFor($(this));<br /> });<br /> });<br /> }<br /> destClicked=true;<br /> });<br /> <br /> //set up drag-and-drop stuff<br /> $("#textInput").draggable(<br /> { connectToSortable:'#destination',<br /> cursor:'move',<br /> helper:'clone',<br /> }<br /> );<br /> $("#longText").draggable(<br /> { connectToSortable:'#destination',<br /> cursor:'move',<br /> helper:'clone',<br /> }<br /> );<br /> $("#selectMultiple").draggable(<br /> { connectToSortable:'#destination',<br /> cursor:'move',<br /> helper:'clone',<br /> }<br /> );<br /> $("#selectOne").draggable(<br /> { connectToSortable:'#destination',<br /> cursor:'move',<br /> helper:'clone',<br /> }<br /> );<br /> $("#destination").sortable(<br /> {<br /> change: function(event, ui) {<br /> ui.placeholder.css({visibility: 'visible', border : '2px solid yellow'});<br /> },<br /> start: function(event, ui) {<br /> ui.placeholder.css({visibility: 'visible', border : '2px solid yellow'});<br /> var tempID=ui.item.attr("id");<br /> if (tempID.indexOf("_")==-1) {<br /> tempID=tempID+"_"+totalItems++;<br /> ui.item.attr({id:tempID});<br /> }<br /> },<br /> stop: function(event, ui) {<br /> //load element details, and ensure they'll show up again when this item is clicked<br /> showEditDetailsFor(ui.item);<br /> ui.item.bind("click", function() {<br /> showEditDetailsFor(ui.item);<br /> });<br /> },<br /> }<br /> );<br /> });<br /><br /> function showEditDetailsFor ( object ) {<br />// object.effect("highlight", {}, 3000);<br /> currentlyEditing=object.attr("id");<br /> if (currentlyEditing==lastEdited)<br /> return;<br /><br /> $(".formLineEdit").hide();<br /> $("#inputOptions").show();<br /><br /> if (object.attr("id").indexOf("textInput")==0) {<br /> var inputLabel = $.trim(object.find(".label").text());<br /> var inputID = object.find("input[name=inputID]").val();<br /> if (inputLabel!="Text Input" || object.find("input[name=inputID]").attr("name")!="inputID") {<br /> $("#textInputEdit").find("input[name=textInputLabel]").val(inputLabel);<br /> $("#textInputEdit").find("input[name=textInputValue]").val(inputID);<br /> }<br /> $("#textInputEdit").show();<br /> }<br /> else if (object.attr("id").indexOf("longText")==0) {<br /> var inputLabel = $.trim(object.find(".label").text());<br /> var inputID = object.find("textarea:first").val();<br /> if (inputLabel!="Long Text" || inputID!="") {<br /> $("#longTextEdit").find("input[name=longTextLabel]").val(inputLabel);<br /> $("#longTextEdit").find("input[name=longTextValue]").val(inputID);<br /> }<br /> $("#longTextEdit").show();<br /> }<br /> else if (object.attr("id").indexOf("selectMultiple")==0) {<br /> var inputLabel = $.trim(object.find(".label:first").text());<br /> var inputID = object.find("input:last").attr("name");<br /> if (inputLabel!="Select Multiple" || inputID!="selectMulti") {<br /> $("#selectMultiEdit").find("input[name=selectMultiLabel]").val(inputLabel);<br /> $("#selectMultiEdit").find("input[name=selectMultiValue]").val(inputID);<br /> blankOption=$("#selectMultiEdit > .selectOption").remove();<br /> var addedChild=false;<br /> object.children(".formInput").each( function() {<br /> optionClone=blankOption.clone();<br /> var optionLabel=$(this).find(".optionLabel").text();<br /> optionClone.find("input[name=multiOptionLabel]").val(optionLabel);<br /> var optionValue=$(this).find("input:first").attr("value");<br /> optionClone.find("input[name=multiOptionValue]").val(optionValue);<br /> cloneRemoveButton = optionClone.find("input[name=removeSelectMultiOption]");<br /> cloneRemoveButton.bind("mouseup", function() {<br /> $(this).parent().remove();<br /> });<br /> $("#selectMultiEdit").append(optionClone);<br /> addedChild=true;<br /> });<br /> if (!addedChild)<br /> $("#selectMultiEdit").append(blankOption);<br /> } //don't show defaults<br /> $("#selectMultiEdit").show();<br /> }<br /> else if (object.attr("id").indexOf("selectOne")==0) {<br /> var inputLabel = $.trim(object.find(".label:first").text());<br /> var inputID = object.find("input:last").attr("name");<br /> if (inputLabel!="Select One" || inputID!="selectOne") {<br /> $("#selectOneEdit").find("input[name=selectOneLabel]").val(inputLabel);<br /> $("#selectOneEdit").find("input[name=selectOneValue]").val(inputID);<br /> blankOption=$("#selectOneEdit > .selectOption").remove();<br /> var addedChild=false;<br /> object.children(".formInput").each( function() {<br /> optionClone=blankOption.clone();<br /> var optionLabel=$(this).find(".optionLabel").text();<br /> optionClone.find("input[name=oneOptionLabel]").val(optionLabel);<br /> var optionValue=$(this).find("input:first").attr("value");<br /> optionClone.find("input[name=oneOptionValue]").val(optionValue);<br /> cloneRemoveButton = optionClone.find("input[name=removeSelectOneOption]");<br /> cloneRemoveButton.bind("mouseup", function() {<br /> $(this).parent().remove();<br /> });<br /> $("#selectOneEdit").append(optionClone);<br /> addedChild=true;<br /> });<br /> if (!addedChild)<br /> $("#selectOneEdit").append(blankOption);<br /> } //don't show defaults<br /> $("#selectOneEdit").show();<br /> }<br /> lastEdited=currentlyEditing;<br /> }<br /><br /><br /> </script><br /><br /></head><br /><body><br /><center><H3>Form Builder</H3></center><br /><div id="success"></div><br /><div id="error"></div><br /><br /><div id="header"><br /> <br /></div><br /><P/><br /><div class="columns"><br /> <div id="source" class="column first"><br /> <b>Form Elements</b><HR/><br /> <div id="textInput" class="formLine"><br /> <div class="label">Text Input</div><div class="formInput"><input name="inputID" /></div><br /> </div><br /> <HR/><br /> <div id="longText" class="formLine"><br /> <div class="label">Long Text</div><br /> <div class="formInput"><textarea name="textarea"></textarea></div><br /> </div><br /> <HR/><br /> <div id="selectMultiple" class="formLine"><br /> <div class="label">Select Multiple</div><br /> <div class="formInput"> <br /> <input type="checkbox" name="selectMulti" value="one" /><br /> <div class="optionLabel">One</div><br /> </div><br /> <div class="formInput"> <br /> <BR/><input type="checkbox" name="selectMulti" value="two" /><br /> <div class="optionLabel">Two</div><br /> </div><br /> </div><br /> <HR/><br /> <div id="selectOne" class="formLine"><br /> <div class="label">Select One</div><br /> <div class="formInput"> <br /> <input type="radio" name="selectOne" value="one" /><br /> <div class="optionLabel">One</div><br /> </div><br /> <div class="formInput"> <br /> <BR/><input type="radio" name="selectOne" value="two" /><br /> <div class="optionLabel">Two</div><br /> </div><br /> </div><br /> </div> <!--source--><br /> <div id="middle" class="column second"><br /> <b>Form</b> (drag elements here)<br /> <HR/><br /> <div id="destination"> </div><br /> <HR/><br /> </div><br /> <div id="details" class="column last"><br /> <div id="detailHeader"><b>Element Details</b><HR/></div><br /> <div id="textInputEdit" class="formLineEdit"><br /> <div class="editHeader"><br /> <b>Text Input</b><br /> <input type="submit" name="textInputSubmit" value="Done" /><br /> <input type="submit" name="delete" value="Delete" /><br /> </div><br /> <BR/><a href="/formHelp#labels" target="_blank">Label</a><input name="textInputLabel" type="text" /><br /> <BR/><a href="/formHelp#ids" target="_blank">ID</a><input name="textInputValue" /><br /> </div><br /> <div id="longTextEdit" class="formLineEdit"><br /> <div class="editHeader"><br /> <b>Long Text</b><br /> <input type="submit" name="longTextSubmit" value="Done" /><br /> <input type="submit" name="delete" value="Delete" /><br /> </div><br /> <BR/><a href="/formHelp#labels" target="_blank">Label</a><input name="longTextLabel" /><br /> <BR/><a href="/formHelp#ids" target="_blank">ID</a><input name="longTextValue" /><br /> </div><br /> <div id="selectMultiEdit" class="formLineEdit"><br /> <div class="editHeader"><br /> <b>Select Multiple</b><br /> <input type="submit" name="selectMultiSubmit" value="Done" /><br /> <input type="submit" name="delete" value="Delete" /><br /> </div><br /> <BR/><a href="/formHelp#labels" target="_blank">Label</a><input name="selectMultiLabel" /><br /> <BR/><a href="/formHelp#ids" target="_blank">ID</a><input name="selectMultiValue" /><br /> <BR/><input type="submit" name="addSelectMultiOption" value="Add Option" /><br /> <HR/><br /> <div id="selectMultiOption" class="selectOption"><br /> <i>Option</i>: <a href="/formHelp#editSelects" target="_blank">Name</a> <input name="multiOptionLabel" size=12/><br /> <BR/><a href="/formHelp#editSelects" target="_blank">Value</a><input name="multiOptionValue" size=12/><br /> <BR/><input type="submit" name="removeSelectMultiOption" value="Remove" /><br /> <HR/><br /> </div><br /> </div><br /> <div id="selectOneEdit" class="formLineEdit"><br /> <div class="editHeader"><br /> <b>Select One</b><br /> <input type="submit" name="selectOneSubmit" value="Done" /><br /> <input type="submit" name="delete" value="Delete" /><br /> </div><br /> <BR/><a href="/formHelp#labels" target="_blank">Label</a><input name="selectOneLabel" /><br /> <BR/><a href="/formHelp#ids" target="_blank">ID</a><input name="selectOneValue" /><br /> <BR/><input type="submit" name="addSelectOneOption" value="Add Option" /><br /> <HR/><br /> <div id="selectOneOption" class="selectOption"><br /> <i>Option</i>: <a href="/formHelp#editSelects" target="_blank">Name</a><input name="oneOptionLabel" size=12/><br /> <BR/><a href="/formHelp#editSelects" target="_blank">Value</a><input name="oneOptionValue" size=12/><br /> <BR/><input type="submit" name="removeSelectOneOption" value="Remove" /><br /> <HR/><br /> </div><br /> </div><br /> </div> <!-- details--><br /></div> <!--columns--><br /><P/><br /><div class="footers"><br /> <div id="formName" class="footer first"><b>Form Name</b>: <input name="formName" value="default" size=10 length=64 /></div><br /> <div id="formVersionNumber" class="footer second"><br /> <b>Version Number</b>:<br /> <input name="formVersion"><br /> </div><br /> <div id="formSubmitButton" class="footer last"><input type="submit" name="saveForm" value="Finished - Save Form!" /></div><br /></div><br /><br /></body><br /></html><br /></PRE><br /><br />Pretty slick, eh?<br /><br />What you do is, you drag form elements from the first column into the second column, where clones are inserted. (That way the element stays in the first column, so you can have an arbitrary number of instances in the second column.) One key thing to note is that clones do not inherit the clonee's bindings, so you have to bind any events after they're created, as shown above in the "stop" event of the "sortable" definition.<br /><br />I would try to explain more, but either you already know JQuery reasonably well, in which case the above is probably pretty clear already, or you don't, in which case it will be Greek. So - just copy and paste the above as HTML, launch it in a browser, and play around with it; it should drag and drop right out of the box.Jonhttp://www.blogger.com/profile/17475458068193351080noreply@blogger.com10tag:blogger.com,1999:blog-259176237881102296.post-81327620261045777862009-09-29T20:39:00.000-07:002009-09-29T21:06:11.962-07:00little bits of context-free iPhone codeWhat it says on the label.<br /><br />First, an example of how to handle Settings in an iPhone app. The way I do it is, I have a "Settings" class, with lots of class get-and-set methods, so at any time you can just call "[Settings getLanguage]"; then, I have a SettingsViewController, to change them. (Yes, you can register them to be changed in the iPhone's Settings app, but since you have to leave your app for that, this is annoying.)<br /><br />Best of all, you don't have to use Core Data. Instead you can use the even simpler NSUserDefault class, like so:<br /><br /><PRE><br />@interface Settings : NSObject {<br /><br />}<br />+(int)getListMax;<br />+(void) setListMax:(int)value;<br />+(NSString*)getLanguage;<br />+(void) setLanguage:(NSString*)language;<br />+(BOOL) doDownload;<br />+(void) setDoDownload:(BOOL)yesno;<br /><br />@implementation Settings<br /><br />//This method does all the work<br />+(id) getSettingFor:(NSString*)key withDefault:(id)defaultValue {<br /> NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];<br /> id value = [defaults objectForKey:key];<br /> if (value==nil) {<br /> [defaults setObject:defaultValue forKey:key];<br /> return defaultValue;<br /> }<br /> return value;<br />}<br /><br />+(int) getListMax {<br /> return [[Settings getSettingFor:@"listMax" withDefault:[NSNumber numberWithInt:500]] intValue];<br />}<br />+(void) setListMax:(int)value {<br /> [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInt:value] forKey:@"listMax"];<br />}<br /><br />+(NSString*) getLanguage {<br /> return [Settings getSettingFor:@"language" withDefault:@"en"];<br />}<br />+(void) setLanguage:(NSString*)language {<br /> [[NSUserDefaults standardUserDefaults] setObject:language forKey:@"language"];<br />}<br /><br />+(BOOL) doDownload {<br /> return [[Settings getSettingFor:@"doDownload" withDefault:[NSNumber numberWithBool:YES]] boolValue];<br />}<br />+(void) setDoDownload:(BOOL)yesno {<br /> [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:yesno] forKey:@"doDownload"];<br />}<br /><br />[...no dealloc, as we never create an instance]<br /><br /></PRE><br /><br />Note that you easily lazy-initialize all your defaults in code, and then let the user overwrite them. How, you ask? Via the SettingsViewController. Which you could create using the Layout Manager; but I prefer to do it programmatically, with a TableViewController, as it looks slicker much easier to add a Setting that way. Also, it lets me show you an example of my TableViewCell pattern. And while we're at it, a UIActionSheet example too. Voila:<br /><br /><br /><PRE><br />@implementation SettingsViewController<br /><br />- (void)viewDidLoad {<br /> [super viewDidLoad];<br />}<br /><br />//Note that we save the settings as we leave the view<br />- (void)viewDidDisappear:(BOOL)animated {<br /> [super viewDidDisappear:animated];<br /> [[NSUserDefaults standardUserDefaults] synchronize];<br />}<br /><br />#pragma mark -<br />#pragma mark TableView methods<br /><br />- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {<br /> return 1;<br />}<br /><br />- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {<br /> //# of settings<br /> return 3;<br />}<br /><br />- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {<br /> if (indexPath.row==0) { //list max<br /> LabelTextFieldCell *cell = (LabelTextFieldCell *)[tableView dequeueReusableCellWithIdentifier:@"LabelTextField"];<br /> if (cell == nil)<br /> cell = [[[LabelTextFieldCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"LabelTextField"] autorelease];<br /> <br /> cell.fieldName = @"listMax";<br /> cell.fieldDisplayName.text = @"List Max";<br /> cell.fieldValue.tag=indexPath.row;<br /> cell.fieldValue.keyboardType = UIKeyboardTypeURL;<br /> cell.fieldValue.autocapitalizationType = UITextAutocapitalizationTypeNone;<br /> cell.fieldValue.delegate=self;<br /> cell.fieldValue.text=[[NSNumber numberWithInt:[Settings getListMax]] stringValue];<br /> }<br /> else if (indexPath.row==1) { // do download<br /> SwitchCell *cell = (SwitchCell *)[tableView dequeueReusableCellWithIdentifier:@"Switch"];<br /> if (cell == nil)<br /> cell = [[[SwitchCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"Switch"] autorelease];<br /><br /> cell.fieldName = @"doDownload";<br /> cell.fieldDisplayName.text = @"Download pages";<br /> cell.mySwitch.tag=indexPath.row;<br /> cell.mySwitch.on=[Settings doDownload];<br /> cell.currentController = self; //we do this so we can respond to changes<br /> }<br /> else if (indexPath.row==3) { //language<br /> ButtonCell *cell = (ButtonCell *)[tableView dequeueReusableCellWithIdentifier:@"Button"];<br /> if (cell == nil)<br /> cell = [[[ButtonCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"Button"] autorelease];<br /><br /> cell.fieldName=@"language";<br /> cell.fieldDisplayName.text=@"Language";<br /> cell.button.tag=indexPath.row;<br /> [cell.button setTitle:[Settings getLanguageName] forState:UIControlStateNormal];<br /> [cell.button addTarget:self action:@selector(changeLanguage) forControlEvents:UIControlEventTouchUpInside];<br /> }<br /> else<br /> return nil;<br />}<br /><br />#pragma mark -<br />#pragma mark UITextFieldDelegate<br /><br />- (BOOL)textFieldShouldReturn:(UITextField *)textField {<br /> [textField resignFirstResponder];<br /> return YES;<br />}<br /><br />- (void)textFieldDidEndEditing:(UITextField *)textField {<br /> if (textField.tag==0) {<br /> //TODO: check that it's a valid int!<br /> [Settings setListMax:[textField.text intValue]];<br /> }<br />}<br /><br />#pragma mark -<br />#pragma mark Switch<br /><br />-(void) valueChanged:(UISwitch*)aSwitch {<br /> if (aSwitch.tag==1) {<br /> [Settings setDoDownload:aSwitch.on];<br /> }<br />}<br /><br />#pragma mark -<br />#pragma mark Button<br /><br />-(void) changeLanguage {<br /> UIActionSheet *action = [[UIActionSheet alloc]<br /> initWithTitle:@"Select Language"<br /> delegate:self<br /> cancelButtonTitle:nil <br /> destructiveButtonTitle:nil<br /> otherButtonTitles:nil];<br /> <br /> for (NSString* language in [Util getValidLanguageNames]) {<br /> [action addButtonWithTitle:language];<br /> }<br /> <br /> [action showInView:self.view];<br />}<br /><br />#pragma mark -<br />#pragma mark UIActionSheetDelegate<br /><br />- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {<br /> [Settings setLanguage:[[Util getValidLanguageValues] objectAtIndex:buttonIndex]];<br /> <br /> UIButton *button = (UIButton*) [self.tableView viewWithTag:6];<br /> [button setTitle:[actionSheet buttonTitleAtIndex:buttonIndex] forState:UIControlStateNormal];<br /> <br /> [actionSheet dismissWithClickedButtonIndex:buttonIndex animated:YES];<br /> [actionSheet release];<br />}<br /><br />[...dealloc etc...]<br /><br /></PRE><br /><br />That's pretty straightforward; build a table view, populate it with table view cells, and respond to the actions in the cells. But how do the cells work? Well, first look at their (theoretically abstract) common parent superclass, ITRTableViewCell:<br /><br /><br /><PRE><br />@interface ITRTableViewCell : UITableViewCell {<br /> NSString *fieldName;<br /> UILabel *fieldDisplayName;<br /> UIViewController *currentController;<br />}<br /><br />@property (nonatomic, retain) NSString *fieldName;<br />@property (nonatomic, retain) UILabel *fieldDisplayName;<br />@property (nonatomic, assign) UIViewController *currentController; //weak reference<br /><br /><br />@implementation ITRTableViewCell<br /><br />@synthesize fieldName, fieldDisplayName, currentController;<br /><br />-(id)initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {<br /> [super initWithFrame:frame reuseIdentifier:reuseIdentifier];<br /> <br /> self.fieldDisplayName = [[UILabel alloc] init];<br /> fieldDisplayName.textAlignment = UITextAlignmentLeft;<br /> fieldDisplayName.adjustsFontSizeToFitWidth=YES;<br /> fieldDisplayName.minimumFontSize=8;<br /> fieldDisplayName.numberOfLines=2;<br /> fieldDisplayName.font = [UIFont systemFontOfSize:14];<br /> <br /> return self;<br />}<br /><br />[...dealloc etc...]<br /></PRE><br /><br />which will make more sense when you look at its use in a subclass:<br /><br /><PRE><br />@interface LabelTextFieldCell : ITRTableViewCell {<br /> UITextField *fieldValue;<br />}<br /><br />@property (nonatomic, retain) UITextField *fieldValue;<br /><br /><br />@implementation LabelTextFieldCell<br /><br />@synthesize fieldValue;<br /><br />-(id)initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {<br /> [super initWithFrame:frame reuseIdentifier:reuseIdentifier];<br /> <br /> [self.contentView addSubview:fieldDisplayName];<br /> <br /> self.fieldValue = [[UITextField alloc] init];<br /> fieldValue.clearsOnBeginEditing = NO;<br /> fieldValue.enablesReturnKeyAutomatically = YES;<br /> fieldValue.returnKeyType = UIReturnKeyNext;<br /> fieldValue.autocapitalizationType = UITextAutocapitalizationTypeSentences;<br /> fieldValue.autocorrectionType = UITextAutocorrectionTypeNo;<br /> fieldValue.enablesReturnKeyAutomatically = YES;<br /> fieldValue.backgroundColor = [self getBackgroundColor];<br /> fieldValue.textColor = [self getTextColor];<br /> fieldValue.textAlignment = UITextAlignmentLeft;<br /> fieldValue.font = [UIFont systemFontOfSize:14];<br /> fieldValue.borderStyle = UITextBorderStyleBezel;<br /> [self.contentView addSubview:fieldValue];<br /> <br /> return self;<br />}<br /><br />-(void)layoutSubviews {<br /> [super layoutSubviews];<br /> CGRect contentRect = self.contentView.bounds;<br /> CGFloat boundsX = contentRect.origin.x;<br /> CGRect frame;<br /> <br /> frame = CGRectMake(boundsX+10, 0, 140, 30);<br /> fieldDisplayName.frame = frame;<br /> <br /> frame = CGRectMake(boundsX+150, 0, 160, 30);<br /> fieldValue.frame = frame;<br />}<br /><br />[...dealloc...]<br /></PRE><br /><br />Ya see? The superclass defines the name on the left; the subclass defines the input on the right with which the user interacts. Here are the ButtonCell and SwitchCell implementations:<br /><br /><PRE><br />@implementation ButtonCell<br /><br />@synthesize button;<br /><br />-(id)initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {<br /> [super initWithFrame:frame reuseIdentifier:reuseIdentifier];<br /> <br /> [self.contentView addSubview:fieldDisplayName];<br /> <br /> self.button = [UIButton buttonWithType:UIButtonTypeRoundedRect];<br /> button.backgroundColor = [self getBackgroundColor];<br /> button.titleLabel.textColor = [self getTextColor];<br /> button.titleLabel.textAlignment = UITextAlignmentLeft;<br /> button.titleLabel.font = [UIFont systemFontOfSize:14]; <br /> [self.contentView addSubview:button];<br /> <br /> return self;<br />}<br /><br />-(void)layoutSubviews {<br /> [super layoutSubviews];<br /> CGRect contentRect = self.contentView.bounds;<br /> CGFloat boundsX = contentRect.origin.x;<br /> CGRect frame;<br /> <br /> frame = CGRectMake(boundsX+10, 0, 140, 30);<br /> fieldDisplayName.frame = frame;<br /> <br /> frame = CGRectMake(boundsX+150, 0, 160, 30);<br /> button.frame = frame;<br />}<br /><br />[...dealloc...]<br /><br />@implementation SwitchCell<br /><br />@synthesize mySwitch;<br /><br />-(id)initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {<br /> [super initWithFrame:frame reuseIdentifier:reuseIdentifier];<br /> <br /> [self.contentView addSubview:fieldDisplayName];<br /> <br /> self.mySwitch = [[UISwitch alloc] init];<br /> mySwitch.backgroundColor = [self getBackgroundColor];<br /> [mySwitch addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventValueChanged];<br /> [self.contentView addSubview:mySwitch];<br /> <br /> return self;<br />}<br /><br />-(void)layoutSubviews {<br /> [super layoutSubviews];<br /> CGRect contentRect = self.contentView.bounds;<br /> CGFloat boundsX = contentRect.origin.x;<br /> CGRect frame;<br /> <br /> frame = CGRectMake(boundsX+10, 0, 140, 30);<br /> fieldDisplayName.frame = frame;<br /> <br /> frame = CGRectMake(boundsX+210, 0, 110, 30);<br /> mySwitch.frame = frame;<br />}<br /><br />-(void)switchAction:(UISwitch*) sender {<br /> [currentController performSelector:@selector(valueChanged:) withObject: sender];<br />}<br /><br />[...dealloc...]<br /></PRE><br /><br />Note the callbacker on the SwitchCell, not necessary on ButtonCell because we can set its target action when we create it.<br /><br /><br />There you go: a Settings architecture, and a programmatic TableViewController with a useful custom TableViewCell architecture and three examples of same. Use as you like.<br /><br /><br />And now, an actual algorithm I wrote. An algorithm! I know! Real programming! Hence my pride. The problem was, given a list of points that might have a few spurious outliers, get rid of those outliers and build a zoomed-in region that excludes them, to show in an MKMapView. My solution, in a class called Locator:<br /><br /><PRE><br />+(MKCoordinateRegion)getRegionForAnnotations:(NSArray*)annotations {<br /><br /> NSMutableArray *latitudes = [NSMutableArray arrayWithCapacity:[annotations count]];<br /> NSMutableArray *longitudes = [NSMutableArray arrayWithCapacity:[annotations count]];<br /><br /> for (id <MKAnnotation> entry in annotations) {<br /> double myLat = [entry coordinate].latitude;<br /> double myLong = [entry coordinate].longitude;<br /> [latitudes addObject:[NSNumber numberWithDouble:myLat]];<br /> [longitudes addObject:[NSNumber numberWithDouble:myLong]];<br /> }<br /><br /> //OK, we've got the box that includes *all* the annotations<br /> //Now we get rid of outliers aka bad address finds.<br /> NSArray *sortedLatitudes = [latitudes sortedArrayUsingSelector:@selector(compare:)];<br /> NSArray *sortedLongitudes = [longitudes sortedArrayUsingSelector:@selector(compare:)];<br /> <br /> NSRange latLongest = [Locator getLongestContiguousRangeIn:sortedLatitudes];<br /> NSRange lonLongest = [Locator getLongestContiguousRangeIn:sortedLongitudes];<br /> <br /> NSNumber* minLat = [sortedLatitudes objectAtIndex:latLongest.location];<br /> NSNumber* maxLat = [sortedLatitudes objectAtIndex:latLongest.location+latLongest.length-1];<br /> NSNumber* minLon = [sortedLongitudes objectAtIndex:lonLongest.location];<br /> NSNumber* maxLon = [sortedLongitudes objectAtIndex:lonLongest.location+lonLongest.length-1];<br /> MKCoordinateRegion regionToShow = [Locator getRegionForMinLat:minLat minLong:minLon maxLat:maxLat maxLong:maxLon];<br /> return regionToShow;<br />}<br /> <br />+(NSRange) getLongestContiguousRangeIn:(NSArray*)numbers {<br /> NSRange longest; longest.location=0; longest.length=0;<br /> NSRange range; range.location=0; range.length=0;<br /> for (int i=0; i<[numbers count]; i++) {<br /> double thisLat = [[numbers objectAtIndex:i] doubleValue];<br /> double lastLat = i>0 ? [[numbers objectAtIndex:i-1] doubleValue] : thisLat;<br /> if (thisLat-lastLat<=(double)1.0)<br /> range.length++;<br /> else {<br /> range.location=i;<br /> range.length=0;<br /> }<br /> if (range.length>longest.length)<br /> longest=range;<br /> }<br /> return longest;<br />}<br /><br />+(MKCoordinateRegion) getRegionForMinLat:(NSNumber*)minLat minLong:(NSNumber*)minLong maxLat:(NSNumber*)maxLat maxLong:(NSNumber*)maxLong {<br /> CLLocationCoordinate2D regionCenter;<br /> regionCenter.latitude=([minLat doubleValue]+[maxLat doubleValue])/2;<br /> regionCenter.longitude=([minLong doubleValue]+[maxLong doubleValue])/2;<br /> <br /> MKCoordinateSpan regionSpan;<br /> regionSpan.latitudeDelta=[maxLat doubleValue]-[minLat doubleValue];<br /> regionSpan.longitudeDelta=[maxLong doubleValue]-[minLong doubleValue];<br /> <br /> MKCoordinateRegion region;<br /> region.center=regionCenter;<br /> region.span = regionSpan;<br /> return region;<br />} <br /></PRE><br /><br />Quite elegant and efficient, if I do say so myself. It would make for an interesting interview question, too.Jonhttp://www.blogger.com/profile/17475458068193351080noreply@blogger.com5tag:blogger.com,1999:blog-259176237881102296.post-52013382967433665812009-09-09T17:39:00.001-07:002009-09-09T17:44:17.282-07:00Weird, man, weirdSo I have switched to the <a href="http://code.google.com/p/google-toolbox-for-mac/wiki/iPhoneUnitTesting">Google Toolbox iPhone unit-test framework</a>, and it mostly works a dream. You plug it in as per those instructions, write some tests, switch to your test target, hit "Build", and it runs your unit tests in the build phase, and highlights test failures in the same way that XCode normally highlights compile errors.<br /><br />However. I have found something profoundly weird about it, which cost me a bunch of today.<br /><br />Suppose your unit test is failing, and you want to debug it. Well, you can; but to do so, you have to not just Build but Run the test target, so you have to comment out the tests that are causing the build to fail. Easy enough. Then the test target launches normally in the simulator, and you can step through with the debugger, and find out what went wrong.<br /><br />However. Guess what? If you leave <i>any breakpoints in your code</i>, and then go back and hit Build, then the Google unit-test framework will begin to fail, in strange and inexplicable ways (mostly null values where there shouldn't be any, in my case.) Remove those breakpoints - and <i>poof</i>, your unit tests are working again.<br /><br />May you not spend a day beating your head against this, as I did.Jonhttp://www.blogger.com/profile/17475458068193351080noreply@blogger.com5tag:blogger.com,1999:blog-259176237881102296.post-19444401569080378982009-09-01T09:31:00.000-07:002009-09-01T09:50:32.574-07:00iPhone bits and bobsHello there, O my droogs. Long time no talk. I've been working on an iPhone app for pay, you see, which I figure kind of limits how much code I can provide you. I do have a few notes that might be worth sharing, though:<br /><br /><UL><br /><LI><b>MapView code</b><br /><P>A fully functional MapViewDelegate implementation for you. All you have to do to start putting items on maps is make them implement MKAnnotation, which is super-easy.<br /><br /><PRE><br />- (MKAnnotationView *)mapView:(MKMapView *)myMapView viewForAnnotation:(id <MKAnnotation>)annotation {<br /> <br /> //this is clumsy, but there's no obvious better way - otherwise it crashes when showing user location<br /> if (![annotation isKindOfClass:[ECEntry class]])<br /> return nil;<br /><br /> ECEntry *myEntry = (ECEntry*)annotation;<br /> <br /> MKPinAnnotationView *myView = (MKPinAnnotationView*)[myMapView dequeueReusableAnnotationViewWithIdentifier:@"Local"];<br /> if (myView==nil)<br /> myView = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"Local"] autorelease];<br /> myView.pinColor = myEntry.groupID==0 ? MKPinAnnotationColorGreen : MKPinAnnotationColorRed;<br /> myView.canShowCallout=YES;<br /> myView.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];<br /> return myView;<br />}<br /><br />- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control {<br /> ECEntryViewController *entryViewController = [[ECEntryViewController alloc] initWithNibName:nil bundle:nil];<br /> entryViewController.myEntry = (ECEntry*)[view annotation];<br /> [self.navigationController pushViewController:entryViewController animated:YES];<br /> [entryViewController release];<br />}<br /></PRE><br /><br /><br /><LI><b>Using the camera via UIImagePickerController</b><br /><P>So this is amazingly easy, and I can even provide you with some code that<br />a) launches a camera, phot-album selector, or photo-library selector, depending on what's available on your device:<br />b) presents the image picker as a modal view controller, keeping it within your existing NavigationController tree:<br />c) gets the selected/captured image (via UIImagePickerControllerDelegate) and saves it to a file.<br /> <br /><PRE><br />-(void) doCamera {<br /> BOOL hasCamera = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];<br /> BOOL hasAlbum = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum];<br /> BOOL hasLibrary = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary];<br /><br /> if (hasCamera || hasAlbum || hasLibrary) {<br /> UIImagePickerController *photoController = [[UIImagePickerController alloc] init];<br /> photoController.delegate = self;<br /><br /> if (hasCamera)<br /> photoController.sourceType = UIImagePickerControllerSourceTypeCamera;<br /> else if (hasAlbum) {<br /> photoController.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;<br /> NSString *warningMessage = [NSString localizedStringWithFormat:@"Your device has no camera, but does have an album of saved photos to choose from"];<br /> [Util doAlert:NSLocalizedString(@"Warning",@"Alert title") withMessage:warningMessage];<br /> }<br /> else if (hasLibrary) {<br /> photoController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;<br /> NSString *warningMessage = [NSString localizedStringWithFormat:@"Your device has no camera, but does have a photo library to choose from"];<br /> [Util doAlert:NSLocalizedString(@"Warning",@"Alert title") withMessage:warningMessage];<br /> }<br /> <br /> [self doSave];<br /> [self presentModalViewController:photoController animated:YES];<br /> [photoController release];<br /> }<br /> else {<br /> NSString *alertMessage = [NSString localizedStringWithFormat:@"Your device does not support photos"];<br /> [Util doAlert:NSLocalizedString(@"No photo support",@"Alert title") withMessage:alertMessage];<br /> }<br />}<br /><br />- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {<br /><br /> UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];<br /> if (image == nil)<br /> image = [info objectForKey:UIImagePickerControllerOriginalImage];<br /><br /> //TODO, if possible: if the image has already been saved, just use its path, don't save it again<br /><br /> if (image!=nil) {<br /> //convert image to NSData - use Settings for PNG/JPG<br /> [Util showActivity];<br /> NSData *imageData=nil;<br /> if ([Settings saveImagesAsPNG])<br /> imageData = [NSData dataWithData:UIImagePNGRepresentation(image)];<br /> else<br /> imageData = [NSData dataWithData:UIImageJPEGRepresentation(image, [Settings getJPEGQuality])];<br /> <br /> //save NSData to file<br /> NSString *pathDir = [Util getApplicationDocumentsPath]; <br /> NSString *fileName = [[NSProcessInfo processInfo] globallyUniqueString];<br /> fileName = [fileName stringByAppendingString:([Settings saveImagesAsPNG] ? @".png" : @".jpg")];<br /> NSString *fullPath = [pathDir stringByAppendingPathComponent:fileName];<br /><br /> NSError *error=nil;<br /> [imageData writeToFile:fullPath options:NSAtomicWrite error:&error];<br /> if (error) {<br /> NSString *errorMessage = [NSString localizedStringWithFormat:@"Unable to write to file %@: %@ - %@", fullPath, error, [error userInfo]];<br /> [Util doAlert:NSLocalizedString(@"Error",@"Alert title") withMessage:errorMessage];<br /> }<br /> [Util stopShowingActivity];<br /> <br /> //set entry<br /> myEntry.photoPath=fileName;<br /><br /> //all done<br /> [self dismissModalViewControllerAnimated:YES];<br /> [self.tableView reloadData];<br /> }<br />}<br /><br />- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {<br /> [self dismissModalViewControllerAnimated:YES];<br /> [self.tableView reloadData];<br />}<br /><br /></PRE><br /><br /><LI><b>Unit test woes</b><br /><P>I've been having loads of trouble with the allegedly-baked-in unit-testing framework described <a href="http://developer.apple.com/IPhone/library/documentation/Xcode/Conceptual/iphone_development/135-Unit_Testing_Applications/unit_testing_applications.html">here</a>. Specifically, I get masses of "symbol(s) not found" linker errors when I try to compile for the Testing target, re all kinds of basic UIKit and CoreData stuff. I presume it's some kind of importing-the-wrong-kind-of-framework problem, but I have no idea how to correct it, and I don't want to dive into the seething nest of rattlesnakes that is the innards of XCode's build process. Should I just switch to the <a href="http://code.google.com/p/google-toolbox-for-mac/wiki/iPhoneUnitTesting">Google unit-test framework for iPhone</a>?<br /></UL>Jonhttp://www.blogger.com/profile/17475458068193351080noreply@blogger.com1tag:blogger.com,1999:blog-259176237881102296.post-76608289826599237652009-08-10T15:06:00.000-07:002009-08-10T15:12:12.027-07:00down in the metalI just wanted to say that I didn't think I would ever write low-level C code again. And yet, here I am:<br /><br /><PRE><br />+(NSNumber *) getRandomDoubleMin:(double)min max:(double)max {<br /> srandomdev();<br /> int nRange = (int) max-min;<br /> int nRand = random() % nRange;<br /> double dRand = (double) nRand;<br /> dRand = dRand+min;<br /> int nRand2 = random() %10000;<br /> double dRand2 = (double)nRand2;<br /> dRand2=dRand2/10000;<br /> dRand=dRand+dRand2;<br /> return [NSNumber numberWithDouble:dRand];<br />}<br /></PRE><br /><br />(It's just a utility function to help populate a map with an assortment of randomly distributed pushpins, for test purposes. But still. Sheesh.)Jonhttp://www.blogger.com/profile/17475458068193351080noreply@blogger.com0tag:blogger.com,1999:blog-259176237881102296.post-77626614923501509772009-08-03T19:51:00.000-07:002009-08-03T20:25:05.911-07:00if you love some source code, set it freeSo I have gone and<UL><LI>a) officially submitted my Wikitravel-editor iPhone app to the App Store <LI>b) released its source code under a BSD open-source license for all to see and play with, at <a href="http://code.google.com/p/itravelwrite/">code.google.com/p/itravelwrite</a>.</UL><br /><br />To be honest I would have liked another few days for cleanup and further testing, but I've gone and gotten a real job (iPhone app development, again) that will occupy me for at least a couple of months, so I had to hurry things up. I apologize for the ugliness of the code.<br /><br />Some of that ugliness is due to its extremely crude testing framework. Unit testing, the panacea of modern software development, is bizarrely difficult to integrate with the iPhone SDK. There are various tools to help you - one created by Google - but they're all far more complex and kludgy than I'd like, especially compared to the elegant joy that is GAEUnit.<br /><br />It turns out, however, that it is possible to seamlessly integrate unit tests and test-driven development into iPhone development with XCode. There are a few caveats, but overall, <a href="http://developer.apple.com/IPhone/library/documentation/Xcode/Conceptual/iphone_development/135-Unit_Testing_Applications/unit_testing_applications.html">these instructions</a> work very well, if you follow them very carefully.<br /><br />The caveat is that you can only run the unit tests on an actual physical device, not in the simulator. Now, in some ways this is actually a bonus - you avoid the "but it works in the simulator!" pitfall, and I have learned that the only way to get a feel for what your UI should be is to work on a real iPhone or iPod Touch, the simulator is disastrously misleading - but it does mean that you'll have to go ahead and shell out the $100 to join the iPhone Developer Program so that you can generate the certificates needed to sign your app and install it on your device.<br /><br />Which in turn is a bit of a hassle. But it's a necessary hassle, and one you should get out of the way as soon as possible. "Build early, build often," is a motto that has served me well for many years.<br /><br />The device-testing is also limited in that you have to specifically select a test target, so you can't automatically run your unit tests every time you build your app. But as long as you remember to unit-test at least daily, and immediately after making major changes, I can't see this as <i>that</i> big a shortcoming.<br /><br />Here's some code to run tests in their own separate database, so that you don't pollute your application's data.<br /><br />Your test case's .h file looks something like this:<br /><PRE><br />// Dependent unit tests mean unit test code depends on an application to be injected into.<br />// Setting this to 0 means the unit test code is designed to be linked into an independent executable.<br />#define USE_DEPENDENT_UNIT_TEST 1<br /><br />#import <SenTestingKit/SenTestingKit.h><br />#import <UIKit/UIKit.h><br />#import "MyAppDelegate.h"<br /><br /><br />@interface MyTestCase : SenTestCase {<br /> NSManagedObjectContext *context;<br />}<br /><br />@end<br /></PRE><br /><br />and its .m:<br /><br /><PRE><br />-(void) setUp {<br /> MyAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];<br /> NSURL *storeUrl = [NSURL fileURLWithPath: [[appDelegate applicationDocumentsDirectory] stringByAppendingPathComponent: @"MyAppTest.sqlite"]];<br /><br /> NSError *error;<br /> NSPersistentStoreCoordinator *persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: [appDelegate managedObjectModel]];<br /> if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:nil error:&error]) {<br /> // Handle error<br /> NSLog(@"Error creating persistent store MyAppTest.sqlite %@, %@", error, [error userInfo]);<br /> }<br /> context = [[NSManagedObjectContext alloc] init];<br /> [context setPersistentStoreCoordinator: persistentStoreCoordinator]; <br />}<br /><br />-(void) tearDown {<br /> [context release];<br />}<br /></PRE>Jonhttp://www.blogger.com/profile/17475458068193351080noreply@blogger.com5tag:blogger.com,1999:blog-259176237881102296.post-77738019288763277552009-07-17T19:24:00.000-07:002009-07-17T19:45:45.318-07:00HttpHelper...it's sort of like Hamburger Helper, only tastier.<br /><br />It's been a week of tweaking, fixing little bugs, spiralling in towards hoped-for perfection. I'm pleased to report that I now have an alpha-test version of my iPhone app up and running on my iPod Touch, and it looks to work a charm. If all goes very well indeed I might submit it to the App Store - where it will ultimately be available for the low low price of $0.00 - by the end of the month.<br /><br />In the meantime, here's a utility class that people might find handy: my HttpHelper singleton. It's not <i>really</i> a class variable, since it seems Objective-C doesn't support them (Oh, Smalltalk, how I miss your class instance variables) but "static" has the same effect, if you code carefully. Like so:<br /><br /><PRE><br />//<br />// HttpHelper.m<br />// iTravelWrite<br />//<br />// Singleton class used to send HTTP requests and forward responses to selectors passed in by the caller.<br />// Created by Jon Evans on 04/07/09.<br />//<br /><br />#import "HttpHelper.h"<br />#import "Util.h"<br /><br />@implementation HttpHelper<br /><br />static HttpHelper *singleton=nil;<br /><br />#pragma mark -<br />#pragma mark Singleton methods<br /><br />+(HttpHelper *) getInstance {<br /> if (singleton==nil)<br /> singleton = [[HttpHelper alloc] init];<br /> return singleton;<br />}<br /><br />+(id)allocWithZone:(NSZone *)zone {<br /> if (singleton == nil) {<br /> singleton = [super allocWithZone:zone];<br /> return singleton;<br /> }<br /> return nil;<br />}<br /><br />-(id)copyWithZone:(NSZone *)zone {<br /> return self;<br />}<br /><br />-(id)retain {<br /> return self;<br />}<br /><br />-(unsigned)retainCount {<br /> return UINT_MAX;<br />}<br /><br />-(void)release {<br /> //pass<br />}<br /><br />-(id)autorelease {<br /> return self;<br />}<br /><br />- (void)dealloc {<br /> [super dealloc];<br />}<br /></PRE><br /><br />All the above is housekeeping stuff to ensure that we only ever have one instance of an HttpHelper. Not that a duplicate would be so disastrous in this case, but hey, if you're writing a singleton, write a singleton, right?<br /><br />Here's the part where it actually does stuff. In particular, it does all the HTTP GETs and HTTP POSTs that your iPhone app will ever need:<br /><br /><PRE><br />#pragma mark -<br />#pragma mark Business logic<br /><br />+(NSURLRequest*) buildRequestWithPostKeys:(NSArray *) postKeys postValues:(NSArray *) postValues urlString:(NSString *)urlString {<br /> <br /> NSMutableString *params=[[NSMutableString alloc] initWithCapacity:1024];<br /> for (int i=0; i<[postValues count]; i++) {<br /> [params appendString:[postKeys objectAtIndex:i]];<br /> [params appendString:@"="];<br /> [params appendString:[postValues objectAtIndex:i]];<br /> [params appendString:@"&"];<br /> }<br /> NSData * paramData = [params dataUsingEncoding:NSUTF8StringEncoding];<br /> <br /> NSURL * url = [NSURL URLWithString:urlString];<br /> NSURLRequestCachePolicy policy = NSURLRequestReloadIgnoringCacheData; // never cache a post response, at least in my app<br /> NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:policy timeoutInterval:10.0];<br /> <br /> NSString *msgLength = [NSString stringWithFormat:@"%d", [paramData length]];<br /> [request addValue: msgLength forHTTPHeaderField:@"Content-Length"];<br /> [request setHTTPMethod:@"POST"];<br /> [request setHTTPBody: paramData];<br /> return request;<br />}<br /><br />+(BOOL) doPost:(NSURLRequest *)request forCaller:(id)caller onSuccess:(SEL)onSuccess onFailure:(SEL)onFailure {<br /> <br /> NSArray *keys = [NSArray arrayWithObjects:@"request", @"caller", @"onSuccess", @"onFailure", nil];<br /> NSArray *values = [NSArray arrayWithObjects:request, caller,<br /> [NSValue valueWithBytes:&onSuccess objCType:@encode(SEL)],<br /> [NSValue valueWithBytes:&onFailure objCType:@encode(SEL)],<br /> nil];<br /> NSDictionary *args = [NSDictionary dictionaryWithObjects:values forKeys: keys];<br /> NSThread* uploadThread = [[NSThread alloc] initWithTarget:[self getInstance] selector:@selector(doHttp:) object:args];<br /> [uploadThread start];<br /> [uploadThread release];<br /> return TRUE;<br />}<br /><br />+(NSURLRequestCachePolicy)getCachePolicyFor:(NSString *)urlString {<br /> /*<br /> Hived out to a separate method because we might fine-tune this later.<br /> <br /> In theory, this will cause the app to use the cache policies set by<br /> wetravelwrite.appspot.com, which as of this writing means 1 hour<br /> for listing information, and 10 hours for searches.<br /> <br /> In the ListingEditController and ListingsViewController we manually wipe<br /> the cache for listings edited by the app.<br /> */<br />// return NSURLRequestUseProtocolCachePolicy;<br /> return NSURLRequestReloadIgnoringCacheData;<br />}<br /><br />+(NSURLRequest *)getURLRequestFor:(NSString *)urlString {<br /> NSURL *url = [NSURL URLWithString:urlString];<br /> NSURLRequestCachePolicy policy = [self getCachePolicyFor:urlString];<br /> NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:policy timeoutInterval:7.5];<br /> return request;<br />}<br /><br />+(BOOL) doGet:(NSString *)urlString forCaller:(id)caller onSuccess:(SEL)onSuccess onFailure:(SEL)onFailure {<br /> NSURLRequest *request = [self getURLRequestFor:urlString];<br /> NSArray *keys = [NSArray arrayWithObjects:@"request", @"caller", @"onSuccess", @"onFailure", nil];<br /> NSArray *values = [NSArray arrayWithObjects:request, caller,<br /> [NSValue valueWithBytes:&onSuccess objCType:@encode(SEL)],<br /> [NSValue valueWithBytes:&onFailure objCType:@encode(SEL)],<br /> nil];<br /> NSDictionary *args = [NSDictionary dictionaryWithObjects:values forKeys: keys];<br /> NSThread* uploadThread = [[NSThread alloc] initWithTarget:[self getInstance] selector:@selector(doHttp:) object:args];<br /> [uploadThread start];<br /> [uploadThread release];<br /> return TRUE;<br />}<br /><br />-(BOOL) doHttp:(NSDictionary *)args<br /> {<br /> @synchronized (self) {<br /> //autorelease pool<br /> NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];<br /> <br /> NSURLRequest *request = [args objectForKey:@"request"];<br /> NSObject *caller = [args objectForKey:@"caller"];<br /> <br /> SEL onSuccess;<br /> [[args objectForKey:@"onSuccess"] getValue:&onSuccess];<br /> SEL onFailure;<br /> [[args objectForKey:@"onFailure"] getValue:&onFailure];<br /> <br /> NSError *error;<br /> NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: &error ];<br /> NSString * responseString = [[NSString alloc] initWithData: returnData encoding: NSASCIIStringEncoding];<br /> <br /> if (!error) //connection succeeded; but did it work?<br /> error = [Util getErrorFrom:responseString forRequest:request];<br /> <br /> if (error) {<br /> NSLog(@"iTravelWrite Error ",error);<br /> [caller performSelectorOnMainThread: onFailure withObject:error waitUntilDone:NO];<br /> }<br /> else<br /> [caller performSelectorOnMainThread: onSuccess withObject:responseString waitUntilDone:NO];<br /> [pool release];<br /> }<br /> return TRUE;<br />}<br /><br />@end<br /></PRE><br /><br />Pretty slick, huh?<br /><br />The three chief interface methods are, for a GET -<br /><br /><PRE><br />+(BOOL) doGet:(NSString *)urlString forCaller:(id)caller onSuccess:(SEL)onSuccess onFailure:(SEL)onFailure<br /></PRE><br /><br />and for a POST -<br /><br /><PRE><br />+(NSURLRequest*) buildRequestWithPostKeys:(NSArray *) postKeys postValues:(NSArray *) postValues urlString:(NSString *)urlString<br /><br />+(BOOL) doPost:(NSURLRequest *)request forCaller:(id)caller onSuccess:(SEL)onSuccess onFailure:(SEL)onFailure {<br /></PRE><br /><br />I'll give you an example of the former first, as it's easier. The call itself is perfectly straightforward:<br /><br /><PRE><br /> NSMutableString *urlString = [NSMutableString stringWithCapacity:128];<br /> [urlString appendString:[Util getSearchPageURL]];<br /> [urlString appendString:@"?locale="];<br /> [urlString appendString:[UserSettings getLanguage]];<br /> [urlString appendString:@"&searchTerms="];<br /> [urlString appendString:[searchBar.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];<br /> [HttpHelper doGet:urlString forCaller:self onSuccess:@selector(parseSearchResults:) onFailure:@selector(searchFailed:)];<br /></PRE><br /><br />Not, however, the two "@selector" arguments. These must be methods on the caller, and they better expect an NSString* and an NSError*, respectively, as arguments. (Or they can take an NSObject* and cast from there, I suppose, but why bother, right?)<br /><br />Inside HttpHelper we have to wrap the selectors in NSValues to pass them from method to method, which is a bit annoying, but hey, we only have to do it once.<br /><br />To call a POST, by comparison:<br /><PRE><br /> NSArray *postKeys = [NSArray arrayWithObjects:@"title", @"location", @"comments", @"pageUri", @"sectionName", @"sectionNumber", @"listingName", nil];<br /> NSArray *postValues = [NSArray arrayWithObjects:note.title, [note locationString], note.body, note.pageUri, note.sectionName, note.sectionNumber, note.listingName, nil];<br /> NSURLRequest *request = [HttpHelper buildRequestWithPostKeys:postKeys postValues:postValues urlString:[Util getUploadNoteURL]];<br /> [HttpHelper doPost:request forCaller:self onSuccess:@selector(onUploadSuccess) onFailure:@selector(onUploadError:)];<br /></PRE><br /><br />Note that "onUploadSuccess" here doesn't take an argument - I don't care about the web site's response, the fact of success is all that matters. OK, dubious wisdom that, but the example is relevant to show that the selector methods don't actually have to accept arguments.<br /><br /><br />We launch a new thread every time we call HttpHelper, so we have to be careful lest we run into concurrency problems. So we synchronize the actual HTTP calls in the "doHttp:" method, which is the one place in the app where we actually go out and connect to the big bad scary Internet.<br /><br />Note also that if we wanted to change from using "sendSynchronousRequest:" to the delegated version of NSURLConnection, the only class that would change is HttpHelper. Ah, encapsulation.<br /><br />Anyway. Share and enjoy, as the man said. Hope all that's useful to someone out there...Jonhttp://www.blogger.com/profile/17475458068193351080noreply@blogger.com0