0

Current scenario: I have successfully implemented the project on one testing device(iOS) with all the functions working. Unfortunately, while running it on other registered devices for testing, it gives following issue

enter image description here issue starting from the following arrow marked in given screenshot of the log:

How it's showing on registered device which is used for testing, that works: enter image description here

How it's showing on rest of the registered devices which is used for testing, that does-not work:

enter image description here

What i tried to fix the error:
1.I have tried to add App sandbox and check incoming and outgoing connection, through entitlements file and build new provisioning

2.Set Arbitary in Transport in info.plist

FYI:The API url is in http:

Following is code used for notifications :

//
//  NotificationsTableViewController.swift

//

import UIKit
import PKHUD
import Alamofire
import EmptyDataSet_Swift

class NotificationsTableViewController: UITableViewController {
    
    var notifications: NotificationsResponse?
    var currentPage = 1
    var totalPage = 0
    
    var aryOfNotificationList = NSMutableArray()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        title = _appDelegate.getLocalize("kNotifications")
        
        //        tableView.emptyDataSetSource = self
        //        tableView.emptyDataSetDelegate = self
        
        tableView.tableFooterView = UIView()
        
        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false
        
        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        //self.getNotifications(page: "\(currentPage)")
        self.fetchNotificationList(page: currentPage)
    }
    
    
    
    // MARK: - Table view data source
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.aryOfNotificationList.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "notificationCell", for: indexPath) as! NotificationTableViewCell
                
        let json = self.aryOfNotificationList.object(at: indexPath.row)as! NSDictionary

        if let str = json.value(forKey: "vTitle")as? String{
            cell.titleLable.text = str
        }
        if let str = json.value(forKey: "vText")as? String{
            cell.detailLable.text = str
        }
        if let str = json.value(forKey: "tCreatedAt")as? Int{
            cell.datLabel.text = getDate(unixdate: str, timezone: "UTC")
        }
     
        return cell
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        let json = self.aryOfNotificationList.object(at: indexPath.row)as! NSDictionary
        if let dic = json.value(forKey: "txParameters")as? NSDictionary{
            
            
            guard let bookId = dic.value(forKey: "iBookId")as? Int else {return}
            
            guard let bookName = json.value(forKey: "vTitle")as? String else {return}
            downloadBookAndSave(bookId: bookId,bookName:bookName)
        }
    }
    
}


extension NotificationsTableViewController: EmptyDataSetSource {
    func title(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
        guard let font = UIFont(name: "NotoSansGujarati", size: 18) else {
            // do something with attributes
            return NSAttributedString(string: "Record not found.")
            
        }
        
        let attributes = [NSAttributedString.Key.font: font, NSAttributedString.Key.foregroundColor: UIColor.secondaryColor]
        
        return NSAttributedString(string: "Record not found.", attributes: attributes)
    }
}

// MARK:- API
extension NotificationsTableViewController {
    
    func fetchNotificationList(page:Int){
        guard let urlEncodedString = (AppConstants.URL.getNotifications + "?pageno=\(page)").addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else {
            return
        }
        HUD.show(.progress)
        let url = URL(string: urlEncodedString)!
        print(url)
        
        var headers: HTTPHeaders = [
            "Content-Type"  : "application/x-www-form-urlencoded",
            "Accept"        : "application/json",
        ]
        
        if let accessToken = User.current?.accessToken {
            headers["Authorization"] = "Bearer \(accessToken)"
        } else if let accessToken = UserDefaults.standard.string(forKey: "AccessToken") {
            headers["Authorization"] = "Bearer \(accessToken)"
        }
        
        AF.request(urlEncodedString, method:.get, parameters:nil, headers: headers)
            .responseJSON { response in
                switch response.result {
                case .success(let value):
                    if let json = value as? NSDictionary{
                        print(json)
                        if let str = json.value(forKey: "totalRecord")as? Int{
                            self.totalPage = str
                        }
                        if let ary = json.value(forKey: "data")as? NSArray{
                            for j in ary{
                                self.aryOfNotificationList.add(j as! NSDictionary)
                            }
                        }
                    }
                    
                    if self.currentPage >= self.totalPage{
                        DispatchQueue.main.async {
                            HUD.hide()
                            self.tableView.delegate = self
                            self.tableView.dataSource = self
                            self.tableView.reloadData()
                        }
                    }else{
                        self.currentPage = self.currentPage + 1
                        self.fetchNotificationList(page: self.currentPage)
                    }
                    
                    
                case .failure(let error):
                    print(error.localizedDescription)
                    DispatchQueue.main.async {
                        HUD.hide()
                    }
                }
            }
    }
    
    func getBookService(bookId: Int) {
        guard let urlEncodedString = (AppConstants.URL.getBook + "?book_id=\(bookId)").addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else {
            return
        }
        HUD.show(.progress)
        let url = URL(string: urlEncodedString)!
        let task = URLSession.shared.dataTask(with: url) { [weak self] (data, response, error) in
            DispatchQueue.main.async {
                HUD.hide()
            }
            if let er = error {
                print(er)
                Utils.showAlertController(with: er.localizedDescription, viewController: self!)
                return
            }
            guard let unwrappedData = data else { return }
            do {
                //print(String(data: unwrappedData, encoding: .utf8))
                let getBooksResponse = try JSONDecoder().decode(GetBookResponse.self, from: unwrappedData)
                guard getBooksResponse.books.count != 0 else {
                    DispatchQueue.main.async {
                        Utils.showAlertController(with: "No book found.", viewController: self!)
                    }
                    return
                }
                DispatchQueue.main.async { [weak self] in
                    for book in getBooksResponse.books {
                        var bookJson =
                            """
                        "id": \(book.bookId),
                        "title": \(book.title),
                        "desc": \(book.content)
                        """
                        _appDelegate.loadString(jsonString: &bookJson, type: .Book, langType: .Gujrati)
                    }
                    
                    Utils.showAlertController(with: "Book is saved", viewController: self!)
                    
                }
            } catch {
                print("json error: \(error)")
            }
        }
        task.resume()
        
    }
    
    func getDate(unixdate: Int, timezone: String) -> String {
        let date = NSDate(timeIntervalSince1970: TimeInterval(unixdate))
        let dayTimePeriodFormatter = DateFormatter()
        dayTimePeriodFormatter.dateFormat = "dd/MM/YYYY"
        dayTimePeriodFormatter.timeZone = (NSTimeZone(name: timezone)! as TimeZone)
        let dateString = dayTimePeriodFormatter.string(from: date as Date)
        return "\(dateString)"
    }
    
    
    func downloadBookAndSave(bookId: Int,bookName:String) {
        guard let urlEncodedString = (AppConstants.URL.getBook + "?book_id=\(bookId)").addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else {
            return
        }
        HUD.show(.progress)
        let url = URL(string: urlEncodedString)!
        let task = URLSession.shared.dataTask(with: url) { [weak self] (data, response, error) in
            DispatchQueue.main.async {
                HUD.hide()
            }
            if let er = error {
                print(er)
                Utils.showAlertController(with: er.localizedDescription, viewController: self!)
                return
            }
            guard let unwrappedData = data else { return }
            do {
                //print(String(data: unwrappedData, encoding: .utf8))
                guard let data = try? JSONSerialization.jsonObject(with: unwrappedData, options: []) as? [String:AnyObject]  else {
                    return
                }
                
                let getBooksResponse = try JSONDecoder().decode(GetBookResponse.self, from: unwrappedData)
                guard getBooksResponse.books.count != 0 else {
                    DispatchQueue.main.async {
                        Utils.showAlertController(with: "No book found.", viewController: self!)
                    }
                    return
                }
                DispatchQueue.main.async { [weak self] in
                    let book = getBooksResponse.books[0]
//                        var bookJson =
//                            """
//                        "id": \(book.bookId),
//                        "title": \(book.title),
//                        "desc": \(book.content)
//                        """
                       // _appDelegate.loadString(jsonString: &bookJson, type: .Book, langType: .Gujrati)
                    do {
                        let data = try Data(book.content.utf8)
                        let parsedBookObject = try JSONDecoder().decode([BookContent].self, from: data) // <-- here
                        //print(parsedBookObject)
                        guard let bookModel:BookModelForJSONConversion? = BookModelForJSONConversion(id: book.bookId, title: book.title, content: parsedBookObject)else {return}
                        guard let bookJSONString = bookModel!.convertToJsonString()else {return}
                            let booksManager = VBBooksManager.init()
                        
                            booksManager.saveBook(bookName: book.title, bookData: bookJSONString)
                            Utils.showAlertController(with: "Book is saved", viewController: self!)
                    }
                    catch let error as NSError{
                        print("error: \(error)")
                    }
                    
                    
                }
            } catch {
                print("json error: \(error)")
            }
        }
        task.resume()
        
    }
}

Following link has the files used in the project: https://github.com/JigarDave102/API_files

  • Did u check this [question](https://stackoverflow.com/questions/42996709/ios-error-code-1003-a-server-with-the-specified-hostname-could-not-be-found)? – udi Feb 02 '22 at 09:37
  • yes and tried using that way to solve, but it didn't fix the current issue . Moreover, there's also one more suspicion behind why it could be happening: As the project is not running properly on my m1 mac Xcode all iOS simulators. hence, i have had to add arm64 to excluded architecture to all the targets, pods. Later , to run the project on actual testing device i have to remove all the exception again every-time.. –  Feb 02 '22 at 10:14

2 Answers2

0

You seem to be calling http and not https. For a few years now, actual iOS device have ATS, which stands for App Transport Security.

That's a system that doesn't allow network requests if they are not https and in addition a secure configuration of https

Apple has a nscurl utility to diagnose issues with the server configuration and it also spits out config you need to put in Info.plist

https://developer.apple.com/documentation/security/preventing_insecure_network_connections/identifying_the_source_of_blocked_connections

Alistra
  • 5,177
  • 2
  • 30
  • 42
  • Above answer worked for me to run on other devices ,but now it works on same wifi only where i developed .. is there any fix out of this? –  Feb 18 '22 at 06:48
  • Chances are that your ISP is doing something fishy with TLS traffic maybe? Run the `nscurl` utility on both networks (where it works and where it does not) and check if there are any differences. There also may be differences in your root certificates, if this is a company vs personal thing. – Alistra Feb 25 '22 at 09:47
0

instead of NSAllowsArbitraryLoads in NSAppTransportSecurity in Info.plist, have you tried your specific domain (vadtaldhambooks.com), like this:

<dict>
    <key>NSAppTransportSecurity</key>
    <dict>
        <key>NSExceptionDomains</key>
        <dict>
            <key>vadtaldhambooks.com</key>
            <dict>
                <key>NSIncludesSubdomains</key>
                <true/>
                <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
                <true/>
            </dict>
        </dict>
    </dict>
    </dict>