不推荐使用Swift Xcode NSURLConnection.sendSynchronousRequest

时间:2016-09-20 12:03:54

标签: ios swift nsurlconnection

我刚刚开始使用iPhone开发,感谢那里的许多人,我得到了一个简单的应用程序。我使用以下代码从mysql数据库中提取数据。代码在commonfun.swift文件中,我保存所有函数,并在需要时从各种swift文件调用。由于通信链接,它将尝试30秒。

一切都很好。它是同步的,因为它将数据加载到函数“end”的数组中并“返回”到调用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中看起来是同步的

感谢

1 个答案:

答案 0 :(得分:0)

var data:NSData? =没有         让信号量:dispatch_semaphore_t = dispatch_semaphore_create(0)         let task = NSURLSession.sharedSession()。dataTaskWithRequest(request,completionHandler:{             taskData,_,错误 - > ()in             data = taskData             如果data == nil,则让error = error {print(error)}             dispatch_semaphore_signal(旗语);         })         task.resume()         dispatch_semaphore_wait(信号量,DISPATCH_TIME_FOREVER)         返回数据