Swift获取变量中的坐标纬度经度
我是一个新手,如果能得到任何帮助,我将不胜感激 我想要我的Poststring的纬度和经度值。 但它表明我的响应字符串是空的 我想在下面的行中输入长代码:Swift获取变量中的坐标纬度经度,swift,delegates,segue,core-location,Swift,Delegates,Segue,Core Location,我是一个新手,如果能得到任何帮助,我将不胜感激 我想要我的Poststring的纬度和经度值。 但它表明我的响应字符串是空的 我想在下面的行中输入长代码: let postString = "latiTude=23&longiTude=12"; 把用户的位置。现在我必须手动输入纬度和经度, 但我想用实际用户的位置来替换它。我不知道怎么做 import Foundation import CoreLocation protocol FeedmodelProtocol: class {
let postString = "latiTude=23&longiTude=12";
把用户的位置。现在我必须手动输入纬度和经度,
但我想用实际用户的位置来替换它。我不知道怎么做
import Foundation
import CoreLocation
protocol FeedmodelProtocol: class {
func itemsDownloaded(items: NSArray)
}
class Feedmodel: NSObject, URLSessionDataDelegate, CLLocationManagerDelegate {
weak var delegate: FeedmodelProtocol!
let locationManager = CLLocationManager() // create Location Manager object
var latitude : Double?
var longitude : Double?
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location: CLLocationCoordinate2D = manager.location?.coordinate else { return }
// set the value of lat and long
latitude = location.latitude
longitude = location.longitude
}
func downloadItems() {
self.locationManager.requestAlwaysAuthorization()
// For use in foreground
// You will need to update your .plist file to request the authorization
self.locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.startUpdatingLocation()
}
let myUrl = URL(string: "http://example.com/stock_service4.php");
let defaultSession = Foundation.URLSession(configuration: URLSessionConfiguration.default)
var request = URLRequest(url:myUrl!)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
var postString = ""
if let lat = latitude, let long = longitude {
locationManager.stopUpdatingLocation()
postString = "lati=\(Int(lat))&longi=\(Int(long))"
// do task here now that postString is not empty
}
request.httpBody = postString.data(using: .utf8)
let task = defaultSession.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(String(describing: error))")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(String(describing: response))")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(String(describing: responseString))")
}
task.resume()
}
func parseJSON(_ data:Data) {
var jsonResult = NSArray()
do{
jsonResult = try JSONSerialization.jsonObject(with: data, options:JSONSerialization.ReadingOptions.allowFragments) as! NSArray;
} catch let error as NSError {
print(error)
}
var jsonElement = NSDictionary()
let stocks = NSMutableArray()
for i in 0 ..< jsonResult.count
{
print(jsonResult)
jsonElement = jsonResult[i] as! NSDictionary
let stock = Stockmodel()
//the following insures none of the JsonElement values are nil through optional binding
if let Datum = jsonElement["Datum"] as? String,
let Tankstelle = jsonElement["Tankstelle"] as? String,
let Kraftstoff1 = jsonElement["Kraftstoff1"] as? String,
let Preis1 = jsonElement["Preis1"] as? String,
let Kraftstoff2 = jsonElement["Kraftstoff2"] as? String,
let Preis2 = jsonElement["Preis2"] as? String,
let Notiz = jsonElement["Notiz"] as? String,
let longitude = jsonElement["longitude"] as? String,
let latitude = jsonElement["latitude"] as? String
{
print (Datum)
print(Tankstelle)
print(Kraftstoff1)
print(Preis1)
print(Kraftstoff2)
print(Preis2)
print(Notiz)
print(longitude)
print(latitude)
stock.Datum = Datum
stock.Tankstelle = Tankstelle
stock.Kraftstoff1 = Kraftstoff1
stock.Preis1 = Preis1
stock.Kraftstoff2 = Kraftstoff2
stock.Preis2 = Preis2
stock.Notiz = Notiz
stock.longitude = longitude
stock.latitude = latitude
}
stocks.add(stock)
}
DispatchQueue.main.async(execute: { () -> Void in
self.delegate.itemsDownloaded(items: stocks)
})
}
}
<代码>导入基础
导入核心定位
协议FeedmodelProtocol:class{
func项目下载(项目:NSArray)
}
类Feedmodel:NSObject、URLSessionDataDelegate、CLLocationManagerDelegate{
弱var委托:FeedmodelProtocol!
让locationManager=CLLocationManager()//创建位置管理器对象
纬度:双倍?
两倍?
func locationManager(manager:CLLocationManager,didUpdateLocations位置:[CLLocation]){
guard let位置:CLLocationCoordinate2D=manager.location?.coordinate else{return}
//设置lat和long的值
纬度=位置。纬度
经度=位置。经度
}
func下载项目(){
self.locationManager.requestAlwaysAuthorization()
//用于前台
//您需要更新.plist文件以请求授权
self.locationManager.requestWhenUseAuthorization()
如果CLLocationManager.locationServicesEnabled(){
locationManager.delegate=self
locationManager.desiredAccuracy=KCallocationAccuracyNearesttenmeters
locationManager.startUpdatingLocation()
}
让myUrl=URL(字符串:http://example.com/stock_service4.php");
让DeFultStase= Fuff.UnLeScript(配置:URLSeSealStutial.Debug)
var request=URLRequest(url:myUrl!)
request.setValue(“application/x-www-form-urlencoded”,forHTTPHeaderField:“内容类型”)
request.httpMethod=“POST”
var postString=“”
如果让lat=纬度,让long=经度{
locationManager.StopUpdatengLocation()
postString=“lati=\(Int(lat))&longi=\(Int(long))”
//既然postString不是空的,就在这里执行任务
}
request.httpBody=postString.data(使用:.utf8)
让task=defaultSession.dataTask(with:request){data,response,中的错误
guard let data=data,error==nil else{//检查基本网络错误
打印(“错误=\(字符串(描述:错误)))
返回
}
如果让httpStatus=响应为?HTTPURLResponse,则httpStatus.statusCode!=200{//检查http错误
打印(“状态代码应为200,但为\(httpStatus.statusCode)”)
打印(“响应=\(字符串(描述:响应)))
}
let responseString=String(数据:数据,编码:.utf8)
打印(“responseString=\(字符串(描述:responseString)))
}
task.resume()
}
func parseJSON(data:data){
var jsonResult=NSArray()
做{
jsonResult=将JSONSerialization.jsonObject(with:data,options:JSONSerialization.ReadingOptions.allowFragments)作为!NSArray;
}将let错误捕获为NSError{
打印(错误)
}
var jsonElement=NSDictionary()
让stocks=NSMutableArray()
对于0中的i..<?php
// Create connection
$con=mysqli_connect("......,......,......,.......");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$firstName= $_REQUEST['latiTude'];
$lastName = $_REQUEST['longiTude'];// Store values in an array
$returnValue = array($latiTude,$longiTude);
// Send back request in JSON format
// Select all of our stocks from table 'stock_tracker'
$sql ="SELECT m. *
, ( ACOS( COS( RADIANS( $latiTude) )
* COS( RADIANS( m.latitude ) )
* COS( RADIANS( m.longitude ) - RADIANS( $longiTude) )
+ SIN( RADIANS($Latitude) )
* SIN( RADIANS( m.Latitude) )
)
* 6371
) AS distance_in_km
FROM TankBilliger m
HAVING distance_in_km <= 100
ORDER BY distance_in_km ASC
LIMIT 100";
// Confirm there are results
if ($result = mysqli_query($con, $sql))
{
// We have results, create an array to hold the results
// and an array to hold the data
$resultArray = array();
$tempArray = array();
// Loop through each result
while($row = $result->fetch_object())
{
// Add each result into the results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
// Encode the array to JSON and output the results
echo json_encode($resultArray);
}
// Close connections
mysqli_close($con);
?>
谢谢大家! 首先需要导入CoreLocation:
import CoreLocation
// and add CLLocationManagerDelegate to the class declaration
然后您需要声明位置管理器和变量以保存lat和long值:
// set these outside of any functions in your class
let locationManager = CLLocationManager() // create Location Manager object
var latitude : Double?
var longitude : Double?
完成后,您需要请求授权以使用设备的位置。您需要将适当的项目(NSLocationAlwaysUsageDescription
,和/或nsLocationWhenUseDescription
I beleive)添加到.plist文件中才能执行此操作
// in the function you want to grab the user's location from
// Ask for Authorisation from the User.
self.locationManager.requestAlwaysAuthorization()
// For use in foreground
// You will need to update your .plist file to request the authorization
self.locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.startUpdatingLocation()
}
然后需要添加函数来检索位置
// Add this function to your program
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location: CLLocationCoordinate2D = manager.location?.coordinate else { return }
// set the value of lat and long
latitude = location.latitude
longitude = location.longitude
}
在所有这些之后,您将能够随时使用纬度和经度变量。您还需要告诉locationManager
,在您获得后停止更新位置
// in the function where you need the postString you can do this
var postString = ""
if let lat = latitude, let long = longitude {
locationManager.stopUpdatingLocation()
postString = "latiTude=\(lat)&longiTude=\(long)"
// do task here now that postString is not empty
}