简体   繁体   English

如何使用 Alamofire + 搜索栏?

[英]How to use Alamofire + Searchbar?

I don't know much about iOS because it's my first time dealing with it.我对 iOS 了解不多,因为这是我第一次接触它。

So I might not have enough explanation.所以我可能没有足够的解释。

I'm sorry about that.我很抱歉。

I would like to use alamofire and Searchbar.我想使用 alamofire 和 Searchbar。

So I'm applying it to various tutorials.所以我将它应用于各种教程。

But now I'm running into an error.但现在我遇到了一个错误。

It's my code.这是我的代码。

import UIKit
import Alamofire
import SwiftyJSON

class MyTableViewController: UITableViewController, UISearchBarDelegate {
    
    var filteredData: [String]!
    var arr_id = [String]()
    var arr_name = [String]()
    
    @IBOutlet weak var mytableview: UITableView!
    @IBOutlet weak var searchBar: UISearchBar!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.mytableview.delegate = self
        self.mytableview.dataSource = self
        searchBar.delegate = self
        
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 0
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell")! as UITableViewCell
        
        cell.textLabel?.text = filteredData[indexPath.row]
        
        return cell
    }
    
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        filteredData = []
        
        let myapiUrl = "http://myurl/test/name.php?name=" + searchText
        
        AF.request(myapiUrl, method: .get).responseJSON { (myresponse) in
            switch myresponse.result {
            case .success:
                print(myresponse.result)
                
                let myresult = try? JSON(data: myresponse.data!)
                print(myresult!)
                
                let resultArray = myresult!
                
                self.arr_id.removeAll()
                self.arr_name.removeAll()
                
                for i in resultArray.arrayValue {
                    let id = i["id"].stringValue
                    self.arr_id.append(id)
                    
                    let name = i["name"].stringValue
                    self.arr_name.append(name)
                }
                self.mytableview.reloadData()
                break
                
            case .failure:
                print(myresponse.error!)
                break
            }
        }
    }
}

There is no error in the code.代码中没有错误。

However, when I run it, the AppDelegate will get an error.但是,当我运行它时,AppDelegate 会出错。

Thread 1: signal SIGABRT

And it's error log.这是错误日志。

2020-10-25 14:57:13.668841+0900 Foodin[5941:314426] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[UITableViewController loadView] instantiated view controller with identifier "UIViewController-BYZ-38-t0r" from storyboard "Main", but didn't get a UITableView.'
*** First throw call stack:
(
    0   CoreFoundation                      0x00007fff23c7127e __exceptionPreprocess + 350
    1   libobjc.A.dylib                     0x00007fff513fbb20 objc_exception_throw + 48
    2   CoreFoundation                      0x00007fff23c710bc +[NSException raise:format:] + 188
    3   UIKitCore                           0x00007fff47a042d7 -[UITableViewController loadView] + 619
    4   UIKitCore                           0x00007fff47a13aca -[UIViewController loadViewIfRequired] + 172
    5   UIKitCore                           0x00007fff47a14277 -[UIViewController view] + 27
    6   UIKitCore                           0x00007fff480ca3cf -[UIWindow addRootViewControllerViewIfPossible] + 150
    7   UIKitCore                           0x00007fff480c9ac0 -[UIWindow _updateLayerOrderingAndSetLayerHidden:actionBlock:] + 232
    8   UIKitCore                           0x00007fff480cab43 -[UIWindow _setHidden:forced:] + 362
    9   UIKitCore                           0x00007fff480ddef1 -[UIWindow _mainQueue_makeKeyAndVisible] + 42
    10  UIKitCore                           0x00007fff482e9431 -[UIWindowScene _makeKeyAndVisibleIfNeeded] + 202
    11  UIKitCore                           0x00007fff4761d445 +[UIScene _sceneForFBSScene:create:withSession:connectionOptions:] + 1405
    12  UIKitCore                           0x00007fff4808f170 -[UIApplication _connectUISceneFromFBSScene:transitionContext:] + 1018
    13  UIKitCore                           0x00007fff4808f4b2 -[UIApplication workspace:didCreateScene:withTransitionContext:completion:] + 304
    14  UIKitCore                           0x00007fff47bfa7f5 -[UIApplicationSceneClientAgent scene:didInitializeWithEvent:completion:] + 361
    15  FrontBoardServices                  0x00007fff365d6165 -[FBSSceneImpl _callOutQueue_agent_didCreateWithTransitionContext:completion:] + 442
    16  FrontBoardServices                  0x00007fff365fc4d8 __86-[FBSWorkspaceScenesClient sceneID:createWithParameters:transitionContext:completion:]_block_invoke.154 + 102
    17  FrontBoardServices                  0x00007fff365e0c45 -[FBSWorkspace _calloutQueue_executeCalloutFromSource:withBlock:] + 220
    18  FrontBoardServices                  0x00007fff365fc169 __86-[FBSWorkspaceScenesClient sceneID:createWithParameters:transitionContext:completion:]_block_invoke + 355
    19  libdispatch.dylib                   0x0000000106eb7d48 _dispatch_client_callout + 8
    20  libdispatch.dylib                   0x0000000106ebacb9 _dispatch_block_invoke_direct + 300
    21  FrontBoardServices                  0x00007fff3662237e __FBSSERIALQUEUE_IS_CALLING_OUT_TO_A_BLOCK__ + 30
    22  FrontBoardServices                  0x00007fff3662206c -[FBSSerialQueue _queue_performNextIfPossible] + 441
    23  FrontBoardServices                  0x00007fff3662257b -[FBSSerialQueue _performNextFromRunLoopSource] + 22
    24  CoreFoundation                      0x00007fff23bd4471 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
    25  CoreFoundation                      0x00007fff23bd439c __CFRunLoopDoSource0 + 76
    26  CoreFoundation                      0x00007fff23bd3bcc __CFRunLoopDoSources0 + 268
    27  CoreFoundation                      0x00007fff23bce87f __CFRunLoopRun + 1263
    28  CoreFoundation                      0x00007fff23bce066 CFRunLoopRunSpecific + 438
    29  GraphicsServices                    0x00007fff384c0bb0 GSEventRunModal + 65
    30  UIKitCore                           0x00007fff48092d4d UIApplicationMain + 1621
    31  Foodin                              0x0000000105c9005b main + 75
    32  libdyld.dylib                       0x00007fff5227ec25 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb) 

You have some problems before Alamofire and SearchBar issue.您在 Alamofire 和 SearchBar 问题之前遇到了一些问题。 Main problem is tableview inheritance..主要问题是tableview继承..

Try to change your Table View class to UITableView from Storyboard or make subclass of your UITableViewController to UiViewController .尝试将您的 Table View 类从 Storyboard 更改为 UITableView 或将您的UITableViewController子类更改为UiViewController

在此处输入图片说明

An UITableViewController has a predefined tableView property. UITableViewController有一个预定义的tableView属性。

Delete the IBOutlet and use the tableView property instead.删除IBOutlet并改用tableView属性。

Notes:笔记:

  • Delete the break keywords in the switch expression.删除switch表达式中的break关键字。 They are not needed in Swift.在 Swift 中不需要它们。
  • Loading (apparently) the same data in textDidChange again and again is unnecessarily inefficient.一次又一次地在textDidChange加载(显然)相同的数据是不必要的低效。 Load the data once and filter it.加载一次数据并过滤它。
  • Multiple arrays as data source is a horrible practice.多个数组作为数据源是一种可怕的做法。 You should look for better tutorials.你应该寻找更好的教程。 Create a custom struct.创建自定义结构。
  • Drop SwiftyJSON in favor of the Codable protocol.放弃SwiftyJSON以支持Codable协议。
  • Never declare a property representing an array as implicit unwrapped optional.永远不要将表示数组的属性声明为隐式解包可选。 Declare it as non-optional empty array.将其声明为非可选的空数组。
  • Don't use those ugly snake_cased variable names.不要使用那些丑陋的snake_cased变量名。 The Swift convention is lowerCamelCase . Swift 约定是lowerCamelCase
  • Never ignore potential errors with try?永远不要忽略try?潜在错误try? - especially during development - and never force unwrap optionals which can be nil . - 尤其是在开发过程中 - 永远不要强制解包可以为nil

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM