Swift Xcode NSURLConnection.sendSynchronousRequest已弃用
问题描述:
我刚开始使用iPhone开发,并感谢许多人在那里,我得到了一个简单的应用程序工作。我正在使用下面的代码从MySQL数据库中提取数据。代码位于commonfun.swift文件中,我保存所有的函数,并且在需要时调用各种swift文件。由于通信链接,它会尝试30秒。Swift Xcode NSURLConnection.sendSynchronousRequest已弃用
这一切都很好。它同步,因为它将数据加载到函数“结尾”的数组中,并“返回”到调用的swift文件。
样品编号如下:
import UIKit
class commonfunc
{
var result1: [String] = [];
func DB_To_Array_Swift(whattoget: String, inout jsondata: NSDictionary)
... set up stuff
... call php to get data
while while_exit == "NO"
{
number_of_retries = number_of_retries + 1
if number_of_retries > 30
{
break
}
do
{
urlData = try NSURLConnection.sendSynchronousRequest(request, returningResponse:&response)
while_exit = "YES"
}
catch let error as NSError
{
tmperror = error
while_exit = "NO"
sleep(1)
}
}
... load data into an array and return to calling swift file.
的伟大工程!并从不同标准的各种swift文件中调用。
现在它说NSURLConnection.sendSynchronousRequest折旧。
我试图用NSURLSession.sharedSession()替换它,但它运行异步并返回到主swift文件。
我试图用下面的替换它。但是.....
while while_exit == "NO"
{
number_of_retries = number_of_retries + 1
if number_of_retries > 30
{
while_exit == "YES"
break
}
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request)
{
(
let urldata, let response, let error) in
if error != nil
{
tmperror = error!
while_exit = "NO"
sleep(1)
}
let dataString = NSString(data: urldata!, encoding: NSUTF8StringEncoding)
print(dataString)
while_exit = "YES"
}
print("\n here5")
task.resume()
print("\n here6")
}
while while_exit == "NO"
{
sleep(1)
}
我有办法使它看起来同步在commonfunc.swift
感谢
答
VAR数据:NSData的? =零 让旗语:dispatch_semaphore_t = dispatch_semaphore_create(0) 令任务= NSURLSession.sharedSession()dataTaskWithRequest(请求,completionHandler:{ taskData,_,错误 - >()在 数据= taskData 如果数据==零,让误差= {错误打印(误差)} dispatch_semaphore_signal(旗语); }) task.resume() dispatch_semaphore_wait(旗语,DISPATCH_TIME_FOREVER) 返回数据
'sleep'很不好,同步网络是非常坏。始终有一种使用异步模式的方法。在你的情况下使用'NSURLSession'和'NSURLSessionDataTask'并实现委托方法。在'didCompleteWithError'中,启动一个计时器并在出错时重新运行任务,或者从接收到的数据创建字符串并继续*将数据加载到数组中并返回调用swift文件*。 – vadian