Swift-OC 單接口網(wǎng)絡(luò)數(shù)據(jù)請(qǐng)求

主頁(yè)面(須要導(dǎo)入OC的Reachability3.0第三方文件(須要導(dǎo)入橋接文件)

Bridging-Header.h ?例:$(SRCROOT)/Swift -- 單接口/Bridging-Header.h)

let?SCR_W =?UIScreen.main.bounds.size.width

let?SCR_H =?UIScreen.main.bounds.size.height

// MARK: ------------------ 給UIViewController添加擴(kuò)展 ------------

extension?UIViewController?{

?//MARK: ---------------- 包裝的提示框 ------------------

?func?showAlert(msg:String,sec:TimeInterval) {

?// 實(shí)例化彈出控制器

?let?alertVC =?UIAlertController(title:?nil, message: msg, preferredStyle: .alert)

?// 從vc控制器彈出提示控制器

?self.present(alertVC, animated:?true, completion:?nil)

?//延時(shí)執(zhí)行隱藏操作

?self.perform(#selector(hideAlertVC(sender:)), with: alertVC, afterDelay: sec)

? ? }


?//隱藏提示框

?@objc?func?hideAlertVC(sender:UIAlertController) {


sender.dismiss(animated:?true, completion:?nil)

? ? }

}

class?RecipeViewController:?UIViewController,UITextFieldDelegate?{


?var?recipeTF:UITextField??// 菜譜輸入的輸入框

?var?searchBtn:UIButton??// 搜索按鈕



?override?func?viewDidLoad() {

?super.viewDidLoad()


?// 設(shè)置View的背景色

?self.view.backgroundColor?=?UIColor.groupTableViewBackground

?recipeTF?=?UITextField(frame:?CGRect(x:?0, y:?0, width:?200, height:?50))

?recipeTF?.center?=?CGPoint(x:?SCR_W/2, y:?SCR_H/2?-?150)

?recipeTF?.borderStyle?= .line

?recipeTF?.placeholder?=?"請(qǐng)輸入查詢的菜譜"

?recipeTF?.textColor?=?UIColor.red

?recipeTF?.clearButtonMode?= .whileEditing

?recipeTF?.textAlignment?= .center

?recipeTF?.delegate?=?self

?self.view.addSubview(recipeTF!)


?searchBtn?=?UIButton(frame:?CGRect(x:?0, y:?0, width:?100, height:?45))

?searchBtn?.center?=?CGPoint(x:?SCR_W/2, y:?SCR_H/2?-?45)

?searchBtn?.setTitle("點(diǎn)擊查詢", for: .normal)

?searchBtn?.backgroundColor?=?UIColor.blue

?searchBtn?.setTitleColor(UIColor.orange, for: .normal)

?searchBtn?.addTarget(self, action:?#selector(searchBtnDidPress(sender:)), for: .touchUpInside)

?self.view.addSubview(searchBtn!)


? ? }


?//MARK: ---------------- 觸摸回調(diào) ---------------------

?@objc?func?searchBtnDidPress(sender:UIButton) {

?if?(recipeTF?.text?.isEmpty)! {

?self.showAlert(msg:?"信息不可為空", sec:?2.5)

?return

? ? ? ? }

?// 實(shí)例化結(jié)果控制器對(duì)象

?let?resultVC =?RecipeResultViewController()

?// 傳遞數(shù)據(jù)

resultVC.passString?=?recipeTF?.text

?//控制器跳轉(zhuǎn)

?self.navigationController?.pushViewController(resultVC, animated:?true)

? ? }

?//MARK: ---------------- UITextFieldDelegate ---------------

?// 點(diǎn)擊return按鈕觸發(fā)回調(diào)

?func?textFieldShouldReturn(_?textField:?UITextField) ->?Bool?{

?// 放棄第一響應(yīng)

? ? ? ? textField.resignFirstResponder()

?return?true

? ? }


?//MARK: ---------------- Touches Methods ---------------

?override?func?touchesBegan(_?touches:?Set, with event:?UIEvent?) {

?super.touchesEnded(touches, with: event)

?recipeTF?.resignFirstResponder()

?// 將view及其子視圖都放棄編輯,如果是TextField就收回鍵盤

?self.view.endEditing(true)

? ? }

}

網(wǎng)絡(luò)數(shù)據(jù)獲取及網(wǎng)絡(luò)狀態(tài)監(jiān)測(cè)封裝的model

class?URLService:?NSObject?{

?//請(qǐng)求搜索的菜譜數(shù)據(jù)

?func?getSearchRecipes(search:String,vc:UIViewController,completion:@escaping?(Any,Bool)->Void) {

?// (1)判斷無(wú)網(wǎng)絡(luò)連接的情況

?if?Reachability.forLocalWiFi().currentReachabilityStatus() ==?NotReachable?&&?Reachability.forInternetConnection().currentReachabilityStatus() ==?NotReachable?{

vc.showAlert(msg:?"網(wǎng)絡(luò)錯(cuò)誤,請(qǐng)檢查錯(cuò)誤", sec:?2.5)

completion("error",false)

?return

? ? ? ? }

?//? (2)狀態(tài)欄中的菊花開始轉(zhuǎn)動(dòng)

?UIApplication.shared.isNetworkActivityIndicatorVisible?=?true

?// (3)網(wǎng)址字符串封裝

?let?url =?URL.init(string:?"http://api.jisuapi.com/recipe/search")

?// (4)創(chuàng)建請(qǐng)求對(duì)象

?var?req =?URLRequest.init(url: url!, cachePolicy: .reloadRevalidatingCacheData, timeoutInterval:?15.0)

?//設(shè)置請(qǐng)求方式為POST

req.httpMethod?=?"POST"

?//將所有的參數(shù)拼接成一個(gè)字符串

?let?str =?"keyword=\(search)&num=40&appkey=de394933e1a3e2db"

?//設(shè)置請(qǐng)求對(duì)象的請(qǐng)求體

req.httpBody?= str.data(using: .utf8)

?// (5)會(huì)話對(duì)象請(qǐng)求服務(wù)器數(shù)據(jù)

?URLSession?.shared.dataTask(with: req) { (data, response, error)?in

?//停止菊花

?DispatchQueue.main.async?{

?UIApplication.shared.isNetworkActivityIndicatorVisible?=?false

? ? ? ? ? ? }

?//如果服務(wù)器連接失敗

?if?error !=?nil?{

?DispatchQueue.main.async?{

vc.showAlert(msg:?"服務(wù)器連接超時(shí)", sec:?2.0)

? ? ? ? ? ? ? ? }

?return

? ? ? ? ? ? }

?//Json解析

?let?jsonData =?try??JSONSerialization.jsonObject(with: data!, options: .allowFragments)


?if?jsonData ==?nil?{

?DispatchQueue.main.async?{

vc.showAlert(msg:?"網(wǎng)絡(luò)數(shù)據(jù)錯(cuò)誤", sec:?2.0)

? ? ? ? ? ? ? ? }

?return

? ? ? ? ? ? }

?//如果正確晦溪,將解析的json數(shù)據(jù)返回給Controller

?let?jsonDic = jsonData?as!?NSDictionary

?let?status = jsonDic.value(forKey:?"status")?as!?NSString

?let?msg = jsonDic.value(forKey:?"msg")?as!?String

?if?status.intValue?!=?0?{

?DispatchQueue.main.async?{

vc.showAlert(msg: msg, sec:?2.0)

? ? ? ? ? ? ? ? }

?return

? ? ? ? ? ? }


?//得到j(luò)son數(shù)據(jù)中result字段對(duì)應(yīng)的字典

?let?resultDic = jsonDic.value(forKey:?"result")?as!?NSDictionary

?//獲取result字典中l(wèi)ist字典

?let?listArr = resultDic.value(forKey:?"list")?as!?NSArray

?//Model封裝

?var?modelArr:[Recipe] = []

?//遍歷數(shù)組中的每一個(gè)字典

?for?item?in?listArr {

?let?itemDic = item?as!?NSDictionary

?let?one =?Recipe()

one.name?= itemDic.value(forKey:?"name")?as??String

one.id?= itemDic.value(forKey:?"id")?as??String

one.content?= itemDic.value(forKey:?"content")?as??String

modelArr.append(one)

? ? ? ? ? ? }


completion(modelArr,true)


}.resume()

? ? }

}

第二個(gè)界面請(qǐng)求的數(shù)據(jù)顯示

class?RecipeResultViewController:?UIViewController,UITableViewDataSource,UITableViewDelegate?{

?var?passString:String?? =?""

?var?tableData:[Recipe]?

?var?table:UITableView?


?//MARK: ------------ UITableViewDataSource -------------


?func?tableView(_?tableView:?UITableView, numberOfRowsInSection section:?Int) ->?Int?{


?if?let?count =?tableData?.count?{

?return?count

? ? ? ? }

?return?0

? ? }


?func?tableView(_?tableView:?UITableView, cellForRowAt indexPath:?IndexPath) ->?UITableViewCell?{

?let?identifier =?"cell"

?var?cell = tableView.dequeueReusableCell(withIdentifier: identifier)

?if?cell ==?nil?{

cell =?UITableViewCell(style: .subtitle, reuseIdentifier: identifier)

? ? ? ? }


?let?one =?self.tableData![indexPath.row]?as??Recipe

cell?.textLabel?.text?= one?.name

cell?.detailTextLabel?.text?= one?.content


?return?cell!

? ? }



?override?func?viewDidLoad() {

?super.viewDidLoad()

?// 設(shè)置View的背景色

?self.view.backgroundColor?=?UIColor.groupTableViewBackground


?self.navigationItem.title?=?"\"\(passString!)的搜索結(jié)果\""


?//實(shí)例化表格視圖

?table?=?UITableView(frame:?CGRect(x:?0, y:?0, width:?SCR_W, height:?SCR_H), style: .plain)

?table?.delegate?=?self

?table?.dataSource?=?self

?table?.rowHeight?=?65

?self.view.addSubview(table!)

? ? }


?override?func?viewWillAppear(_?animated:?Bool) {

?let?urlser =?URLService()

urlser.getSearchRecipes(search:?self.passString!, vc:?self) { (data, success)?in

?if?!success {

?return

? ? ? ? ? ? }

?self.tableData?= data?as? [Recipe]

?DispatchQueue.main.async?{

?self.table?.reloadData()

? ? ? ? ? ? }

? ? ? ? }

? ? }

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末桑涎,一起剝皮案震驚了整個(gè)濱河市萨蚕,隨后出現(xiàn)的幾起案子印屁,更是在濱河造成了極大的恐慌莺禁,老刑警劉巖兴想,帶你破解...
    沈念sama閱讀 211,042評(píng)論 6 490
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件幢哨,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡嫂便,警方通過(guò)查閱死者的電腦和手機(jī)捞镰,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 89,996評(píng)論 2 384
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)毙替,“玉大人岸售,你說(shuō)我怎么就攤上這事〕Щ” “怎么了凸丸?”我有些...
    開封第一講書人閱讀 156,674評(píng)論 0 345
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)袱院。 經(jīng)常有香客問(wèn)我屎慢,道長(zhǎng),這世上最難降的妖魔是什么忽洛? 我笑而不...
    開封第一講書人閱讀 56,340評(píng)論 1 283
  • 正文 為了忘掉前任腻惠,我火速辦了婚禮,結(jié)果婚禮上欲虚,老公的妹妹穿的比我還像新娘集灌。我一直安慰自己,他們只是感情好苍在,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,404評(píng)論 5 384
  • 文/花漫 我一把揭開白布绝页。 她就那樣靜靜地躺著荠商,像睡著了一般。 火紅的嫁衣襯著肌膚如雪续誉。 梳的紋絲不亂的頭發(fā)上莱没,一...
    開封第一講書人閱讀 49,749評(píng)論 1 289
  • 那天,我揣著相機(jī)與錄音酷鸦,去河邊找鬼饰躲。 笑死,一個(gè)胖子當(dāng)著我的面吹牛臼隔,可吹牛的內(nèi)容都是我干的嘹裂。 我是一名探鬼主播,決...
    沈念sama閱讀 38,902評(píng)論 3 405
  • 文/蒼蘭香墨 我猛地睜開眼摔握,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼寄狼!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起氨淌,我...
    開封第一講書人閱讀 37,662評(píng)論 0 266
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤泊愧,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后盛正,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體删咱,經(jīng)...
    沈念sama閱讀 44,110評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,451評(píng)論 2 325
  • 正文 我和宋清朗相戀三年豪筝,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了痰滋。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 38,577評(píng)論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡续崖,死狀恐怖敲街,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情袜刷,我是刑警寧澤聪富,帶...
    沈念sama閱讀 34,258評(píng)論 4 328
  • 正文 年R本政府宣布,位于F島的核電站著蟹,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏梢莽。R本人自食惡果不足惜萧豆,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,848評(píng)論 3 312
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望昏名。 院中可真熱鬧涮雷,春花似錦、人聲如沸轻局。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,726評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至览爵,卻和暖如春置鼻,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背蜓竹。 一陣腳步聲響...
    開封第一講書人閱讀 31,952評(píng)論 1 264
  • 我被黑心中介騙來(lái)泰國(guó)打工箕母, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人俱济。 一個(gè)月前我還...
    沈念sama閱讀 46,271評(píng)論 2 360
  • 正文 我出身青樓嘶是,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親蛛碌。 傳聞我的和親對(duì)象是個(gè)殘疾皇子聂喇,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,452評(píng)論 2 348

推薦閱讀更多精彩內(nèi)容