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

相關文章
相關標籤/搜索