使用Swift的Google Places API网络服务返回错误303 [英] Google Places API web service using swift returns error 303

查看:65
本文介绍了使用Swift的Google Places API网络服务返回错误303的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过iOS(使用swift)使用Google Places Web服务.我要这样做的原因-我想允许浏览地图上的地点,即使它们不在附近(使用iOS提供的库也只能进行搜索).我还需要以编程方式进行操作(因为在一个用例中,我希望允许浏览地图,而在另一种用例中,我希望位置保持不变,并且不会因地图摄像机而改变).我无法使用iOS地点选择器,因为我希望地图显示有关其上地点的信息(并且在一个用例中不要更改)...(如果您对这个问题有更好的设计思路,请告诉我.)

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..)

调用Google Places API网络服务时,出现错误303.在Google API网络服务上,它不计算调用次数,因此我认为它失败了,尽管应该重定向303.

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.

我建立了一个用于与Web服务通信的类(我将服务器地址保存在配置中).此类的结构也可以立即提供结果(而不是在回调中).

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?

谢谢!

这是我的代码的(模板)-我减少了很多逻辑,而放弃了对Web服务的调用(PlaceMarker只是我返回的一个类,您可以将其修改为String):

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);
    }
}

推荐答案

所以我遇到的问题出在这里:

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: []);

出现-此解决方案强制重定向.我不知道函数 addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed),所以我想使用httpBody传输GET数据,这显然是错误的...

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...

将代码更改为:

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";

为我解决了这个问题.注意 query 是对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

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

这篇关于使用Swift的Google Places API网络服务返回错误303的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆