C#与Swift异步操做的差别

  做为一个从C#转到Swift的小菜鸡。。。最近作一个简单的请求API解析Json数据的小程序上碰到一堆小问题。尤为是在异步请求的时候,用惯了C#的async/await写法,在写Swift的时候也按着这个逻辑来作。结果发现回调函数没执行就直接返回了一个空数据出去致使程序一直崩溃(马丹啊)。查了老半天、问了一大堆人最后一个群友的一句话把我点醒了。。。。小程序

  Swift的回调函数异步执行,它并无C#的await来等待它执行完,它是直接往下执行程序的,这个时候你的回调函数并无执行完。因此不能像C#那样用await等待异步操做把数据返回出来,而后对这个数据进行操做。而应该是把你对数据的处理方法用一个Closure传进异步方法里去。下面Po上个人错误代码和修改正确后的代码api

✅正确代码:app

WeatherDataSource.GetWeather("北京") { (weatherdata) in
            NSLog(weatherdata.showapiResBody.cityInfo.c3 + "天气信息:" + weatherdata.showapiResBody.now.weather)
        }


 static func GetWeather(cityName:String,callback:(weatherdata:WeatherRootClass)->Void){
        let request = ShowApiRequest(url: "https://route.showapi.com/9-2", appId: AppInfo.appId, secret: AppInfo.secret)
        request.post(["area":"北京"],  callback: { (data) -> Void in
            let weatherinfo = WeatherRootClass(fromDictionary: data)
            NSLog(weatherinfo.showapiResBody.cityInfo.c3 + "天气信息:" + weatherinfo.showapiResBody.now.weather)
            callback(weatherdata: weatherinfo)
        })
    }

❌错误代码:异步

        var weatherinfo = WeatherRootClass()
        weatherinfo = WeatherDataSource.errorGetWeather("北京")
        NSLog(weatherinfo.showapiResBody.cityInfo.c3 + "天气信息:" + weatherinfo.showapiResBody.now.weather)
    

 static func errorGetWeather(cityName:String) -> WeatherRootClass{
        var result = WeatherRootClass()
        let request = ShowApiRequest(url: "https://route.showapi.com/9-2", appId: AppInfo.appId, secret: AppInfo.secret)
        request.post(["area":"北京"],  callback: { (data) -> Void in
            let weatherinfo = WeatherRootClass(fromDictionary: data)
            result = weatherinfo
        })
        return result
    }

 

还有一个小问题是String转化为NSURL时String内包含有中文转换出来的NSURL就为nilasync

对此的解决办法是:函数

str = str.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!post

let nsurl =NSURL(string: str)!url

将String使用NSUTF8转码,而后使用转码后的String转化为NSURLspa

相关文章
相关标签/搜索