我使用一组信息创建了一个对OnRadar的请求来创建地理围栏。但是,我尝试创建时间/延迟并不会阻止for循环每秒触发超过十次,这是API无法处理的。
func setUpGeofences(){
for object in geofenceArray{
let params: [String: Any] = [
"description": object.name,
"tag": object.tag,
"externalId": object.externalID,
"type": "circle",
"coordinates": [object.lat, object.long],
"radius": object.radius,
]
let headers = ["Authorization: Key"]
let rq = Alamofire.request("https://www.onradar.com/api/v1/geofences", method: .post, parameters: params, encoding: URLEncoding.httpBody, headers: headers)
.responseJSON { response in
print(response.result.value)
print(response.result.error)
}
}
}
这是我使用for循环的功能。我看了几个例子,但是当我试图将它们应用到我自己的工作中时,我没有成功。此外,一旦为我的数组中的每个位置创建了地理围栏,我将如何阻止循环运行?
答案 0 :(得分:1)
这是在请求完成后执行下一个的简单方法:
将geofenceArray: [Geo]
更改为geofenceArray
func setUpGeofences(geofenceArray: [Geo]) {
if let object = geofenceArray.first {
let params: [String: Any] = [
"description": object.name,
"tag": object.tag,
"externalId": object.externalID,
"type": "circle",
"coordinates": [object.lat, object.long],
"radius": object.radius,
]
let headers = ["Authorization: Key"]
let rq = AlamofireRequest("https://www.onradar.com/api/v1/geofences", method: .post, parameters: params, encoding: URLEncoding.httpBody, headers: headers)
.responseJSON { response in
print(response.result.value)
print(response.result.error)
// do the next one
setUpGeofences(geofenceArray: Array(geofenceArray.dropFirst()))
}
}
}
它不能保证每秒慢于10次,但现在这可能还不错。
答案 1 :(得分:0)
他们在这些情况下很难,试试这个:
var i = 0
let geofencesArray = ["firstObject", "secondObject", "thirdObject"]
func iterate(array: [String]) {
if i > array.count-1 {
return
} else {
print(array[i])
i+=1
iterate(array: array)
}
}
iterate(array: geofencesArray)