Search code examples
swiftgoogle-apigoogle-places-apinsurlsessionnsurlrequest

Google Places API web service using swift returns error 303


I am trying to use the Google Places Web Service through iOS (using swift). The reason I want to do so - I want to allow browsing places on a map, even if they are not nearby (the only search allowed using the iOS provided library). I also need to do it programmatically (since in one use-case I want to allow browsing the map, while in another use case - I want the places to be constant and not change based on the map camera). I can't use the iOS place picker, since I want the map to display information about the places on it (and in one use-case to not change)... (If you have a better design idea for this problem, let me know..)

When calling the Google Places API web service I get error 303. On the Google API web service it doesn't count the call, so I assume it failed, although 303 should be redirect.

I built a class for communicating with the web service (I save the server address in the configuration). This class is also structured in a way to provide the results immediately (and not in a callback).

Why do I get an error instead of a redirect? Is there any way to handle it? Any ideas to what can I do to avoid redirection at all?

Thanks!!

Here is (a template) of my code -- I reduced much of my logic and left the call for the web service (PlaceMarker is just a class I return, you can modify it to String):

class GooglePlacesWS : NSObject, NSURLConnectionDelegate, NSURLConnectionDataDelegate , URLSessionDelegate{

var DataReady : Bool!;
var Data : Foundation.Data!;
var opQueue : OperationQueue!;
var _responseData : NSMutableData!;
var error = false;

func getPlacesNear(_ point : CLLocationCoordinate2D, _ radius: Double)->[PlaceMarker]!
{
    var retVal  = [PlaceMarker]();

    var locationJson = ["location": String(format:"%f, %f",point.latitude,point.longitude), "key": “MyKey”];

    if (radius > 0){
        locationJson["raidus"] = String(format:"%d",Int(radius));
    }

    // Fires the request to the server
    var reply : String = HtmlToText(FireRequest(locationJson));
    if reply == "" { return nil}

    return retVal;
}

//MARK: Connection

var session : URLSession? = nil;
var dataTasks : URLSessionTask? = nil;

func sendRequestNew(_ request : URLRequest)
{
    DataReady = false;
    Data = nil;

    let task = session!.dataTask(with: request, completionHandler: {data, response,error in

        if (error != nil){

            NSLog("Error reading data from web service: " + error!.localizedDescription);
            self.Data = nil;
            self.error = true;
            self.DataReady = true;
        }
        else{
            if (data != nil){
                self.Data = data;
                OSMemoryBarrier();
                self.DataReady = true;
            }
        }

    });
    task.resume();
    dataTasks = task;
}

// Changes a string to an HTML friendly tags (so the XML will transfer a string)
func textToHtml (_ htmlString : String) -> String
{
    var retHtml = htmlString;
    retHtml = retHtml.replacingOccurrences(of: "&",  with: "&");
    retHtml = retHtml.replacingOccurrences(of: "<",  with: "&lt;");
    retHtml = retHtml.replacingOccurrences(of: ">",  with: "&gt;");
    retHtml = retHtml.replacingOccurrences(of: "\"", with: "&quot;");
    retHtml = retHtml.replacingOccurrences(of: "'",  with: "&#039;");
    //retHtml = retHtml.stringByReplacingOccurrencesOfString("\n", withString: "<br>");
    return retHtml;
}

// Changes an HTML string to a regular xml (changes the & tags to actual signs)
func HtmlToText(_ textString : String)->String
{
    var retString: String = textString;
    retString = retString.replacingOccurrences(of: "&amp;",  with:"&");
    retString = retString.replacingOccurrences(of: "&lt;",  with:"<");
    retString = retString.replacingOccurrences(of: "&gt;",  with:">");
    retString = retString.replacingOccurrences(of: "&quot;", with:"\"");
    retString = retString.replacingOccurrences(of: "&#039;",  with:"'");
    retString = retString.replacingOccurrences(of: "<br>", with:"\n");
    return retString;
}


// Sends the request to the server
func FireRequest (_ query : [String:String]) ->String
{
    var retVal : String = "";

    do{
        // Builds the final URL request (adds the headers, and the WS addy)
        let config :UserDefaults = UserDefaults();
        //var myDict: NSDictionary?
        if let path : String = config.object(forKey: "googleServerAddy") as? String
        {
            let url = URL(string: path);
            //let theRequest = NSMutableURLRequest(url: url!);
            var request = URLRequest(url: url!);
            request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
            request.httpMethod = "GET";
            request.httpBody = try JSONSerialization.data(withJSONObject: query, options: []);


            sendRequestNew(request);

            while (DataReady == false)
            {
                Thread.sleep(forTimeInterval: 0.01);
            }

            if (!error)
            {
                let result : Foundation.Data = Data!;

                // Reads the response...
                retVal = NSString(data: result, encoding:String.Encoding.utf8.rawValue)! as String;
            }
            else
            {
                retVal = "";
            }
        }
    }
    catch{

    }

    return retVal;
}


//MARK: NSURLConnection delegates
func connection(_ connection: NSURLConnection, willSend request: URLRequest, redirectResponse response: URLResponse?) -> URLRequest? {

    return request;
}


override init() {
    super.init();

    opQueue = OperationQueue();

    session = URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: opQueue);
    }
}

Solution

  • So the problem I had is sourced here:

    let url = URL(string: path);
    var request = URLRequest(url: url!);
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.httpMethod = "GET";
    request.httpBody = try JSONSerialization.data(withJSONObject: query, options: []);
    

    It appears - this solution forces a redirect. I was not aware of the function addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed) so I wanted to use the httpBody for transferring the GET data, which apparently is wrong...

    Changing the code to:

    let actPath = path + "?" + query;
    let url = URL(string: actPath);
    var request = URLRequest(url: url!);
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.httpMethod = "GET";
    

    solved the issue for me. notice query is the query for the get string -- something like

    location=1.1, 2.2&radius=5&key=MY_KEY