我正在尝试通过iOS使用Google Places Web服务(使用swift)。 我想这样做的原因 - 我想允许在地图上浏览地点,即使它们不在附近(允许使用iOS提供的库的唯一搜索)。 我还需要以编程方式进行(因为在一个用例中我想允许浏览地图,而在另一个用例中 - 我希望这些地方是恒定的而不是基于地图相机而改变)。 我无法使用iOS地方选择器,因为我希望地图显示有关其上的位置的信息(并且在一个用例中不会更改)... (如果您对此问题有更好的设计理念,请告诉我们。)
调用Google Places API网络服务时,我收到错误303。 在Google API网络服务上,它不会对通话进行计数,因此我认为它失败了,尽管303应该重定向。
我构建了一个用于与Web服务通信的类(我在配置中保存了服务器地址)。 此类的结构也是为了立即提供结果(而不是在回调中)。
为什么我会收到错误而不是重定向? 有办法处理吗? 有什么想法可以做些什么来避免重定向?
谢谢!
这是我的代码的(模板) - 我减少了很多逻辑并留下了对Web服务的调用(PlaceMarker只是我返回的一个类,你可以将它修改为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: "<");
retHtml = retHtml.replacingOccurrences(of: ">", with: ">");
retHtml = retHtml.replacingOccurrences(of: "\"", with: """);
retHtml = retHtml.replacingOccurrences(of: "'", with: "'");
//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: "&", with:"&");
retString = retString.replacingOccurrences(of: "<", with:"<");
retString = retString.replacingOccurrences(of: ">", with:">");
retString = retString.replacingOccurrences(of: """, with:"\"");
retString = retString.replacingOccurrences(of: "'", 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);
}
}
答案 0 :(得分:1)
你可以使用Alamofire,工作正常。用它来谷歌街景图像
import Foundation
import Alamofire
import AlamofireImage
class GoogleData {
static let dataService = GoogleData()
func getGoogleImages(_ latitude: Double, longitude: Double, heading: Double, id: String, key: Int){
let url = "https://maps.googleapis.com/maps/api/streetview?size=400x300&location=" + String(latitude) + "," + String(longitude) + "&heading=" + String(heading) + "&fov=120&&pitch=-0.76&key=" + GOOGLE_API_KEY
Alamofire.request(url).responseImage { (response) -> Void in
print(response)
guard let image = response.result.value else { return }
print("alamo \(url) ")
let returnObj = [image]
ImageUtils.saveGoogleImageToFile(image , key: key, id: id)
NotificationCenter.default.post(name: NSNotification.Name(rawValue: googleGetImagesNotificationKey), object: returnObj)
}
}
}
称呼它:
GoogleData.dataService.getGoogleImages(yourlatitude, longitude: your.longitude, heading: someHeading, id: someId, key: someKey )
答案 1 :(得分:0)
所以我遇到的问题来自:
addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)
看来 - 此解决方案会强制重定向。
我不知道函数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";
所以我想使用httpBody来传输GET数据,这显然是错误的......
将代码更改为:
query
为我解决了这个问题。
notice children.push(child)
是get字符串的查询 - 类似于
location = 1.1,2.2&amp; radius = 5&amp; key = MY_KEY