Application communicates with database on iOS simulator but not on device - ios

Good evening,
I have a table view that gets populated with data from my local MySQL database. I'm using MAMP along with PHPmyadmin.
It works perfectly fine on the simulator, as you can see:
Working Database
However, when I try to run it on my iPhone device, it doesn't load anything:
Not working Database
What could be the cause for that? I don't really get the difference between the simulator and the device.
The code looks like this:
let url: URL = URL(string: urlPath)!
let defaultSession = Foundation.URLSession(configuration: URLSessionConfiguration.default)
let task = defaultSession.dataTask(with: url) { (data, response, error) in
if error != nil {
print("Failed to download data")
}else {
print("Data downloaded")
self.parseJSON(data!)
}
It prints "Data Downloaded" when on simulator and "Failed to download data" on the device.
I'm using Xcode 9 and Swift 4.
Thanks a lot for your help

Related

URLSession request: request Code=-1009 "(null)" UserInfo={_NSURLErrorNWPathKey=unsatisfied (Denied over cellular interface)

Test is performed on iPhone 13 Pro 15.3.1, with Xcode 13.2.1. I have narrow down the issue as below two tests. The test code below just send a simple https request.
I have allowed the network access for the test app on both Wifi and cell. And I'm a paid developer.
All following two tests are passed in simulator but failed on iPhone, so it means something is wrong in my iPhone side, find a post said China brand iPhone may have this issue, still digging...orz
The error exists with WiFi and Cellular. URLSession request is denied on both Wi-Fi interface and cellular interface.
NSURLErrorNWPathKey=unsatisfied...
1st test:
The test code is provided in Apple doc (https://developer.apple.com/documentation/xctest/asynchronous_tests_and_expectations/testing_asynchronous_operations_with_expectations).
func testDownloadWebData() {
// Create an expectation for a background download task.
let expectation = XCTestExpectation(description: "Download apple.com home page")
// Create a URL for a web page to be downloaded.
let url = URL(string: "https://apple.com")!
// Create a background task to download the web page.
let dataTask = URLSession.shared.dataTask(with: url) { (data, _, _) in
// Make sure we downloaded some data.
XCTAssertNotNil(data, "No data was downloaded.")
// Fulfill the expectation to indicate that the background task has finished successfully.
expectation.fulfill()
}
// Start the download task.
dataTask.resume()
// Wait until the expectation is fulfilled, with a timeout of 10 seconds.
wait(for: [expectation], timeout: 10.0)
}
2nd attempt:
I also try my version, but get the same result.
func testDownloadWebData() {
// Create an expectation for a background download task.
let expectation = expectation(description: "Download apple.com home page")
// Create a URL for a web page to be downloaded.
let url = URL(string: "https://apple.com")!
var request = URLRequest(url: url)
request.httpMethod = "GET"
let config = URLSessionConfiguration.default
config.waitsForConnectivity = true
let session = URLSession(configuration: config)
// Create a background task to download the web page.
let dataTask = session.dataTask(with: request) { (data, _, error) in
// put a breakpoint here, no triggered.
guard error == nil else {
print(error!.localizedDescription)
return
}
// Make sure we downloaded some data.
XCTAssertNotNil(data, "No data was downloaded.")
// Fulfill the expectation to indicate that the background task has finished successfully.
expectation.fulfill()
}
// Start the download task.
dataTask.resume()
// Wait until the expectation is fulfilled, with a timeout of 10 seconds.
wait(for: [expectation], timeout: 10.0)
}

AVPlayer / AVAudioPlayer - Play audio fileURL from iCloud Drive (work on simulator but not iPhone) + (OSStatus error -54.)

I'm making Audio Player.
Importing file from iCloud Drive using .fileImporter.
I get file URL that looks like this: file:///private/var/mobile/Library/Mobile%20Documents/com~apple~CloudDocs/_Storage/Audio-books/%D0%91%D1%80%D0%B5%D0%BD%D0%B4%D1%8F%D1%82%D0%B8%D0%BD%D0%B0/Audiobook.mp3"
Then I pass it to audio player (tried AVPlayer and AVAudioPlayer). Both works on iOS simulator.
On the device after import I get error: The operation couldn’t be completed. (OSStatus error -54.)
I know it's possible, app called Evermusic does quite the same with on device files.
Is there permissions I need to be granted to play audio that stored on device?
How can I access Container for com~apple~CloudDocs?
Thank you very much for help, any suggestions greatly appreciated, I'm seriously stuck.
For future references repo of the project: https://github.com/yaosamo/AudioPlayer
You need to be using startAccessingSecurityScopedResource in order to get read access to those files. See documentation:
https://developer.apple.com/documentation/foundation/nsurl/1417051-startaccessingsecurityscopedreso
https://developer.apple.com/documentation/corefoundation/1543318-cfurlstartaccessingsecurityscope
In addition to #jnpdx answer want to add some details, and my solution example.
Few core things
✅ for my app if you need to access secured audio you need to use startAccessingSecurityScopedResource()
❌ you can't simple store URL and use it later, in fact you don't store fileURL at all. You need to use what's called bookmarkData() on your URL and store it. So later you can restore URL
✅ Watch Apple pres here
Here's how I import file:
.fileImporter(isPresented: $presentImporter, allowedContentTypes: [.mp3]) { result in
switch result {
case .success(let url):
// Start accessing secured url
let StartAccess = url.startAccessingSecurityScopedResource()
defer {
// Must stop accessing once stop using
if StartAccess {
url.stopAccessingSecurityScopedResource()
}
}
// Creating new book
let newBook = Book(context: viewContext)
let _ = print("---- Access Granted?", url.startAccessingSecurityScopedResource())
// Getting bookmarkData of the URL
let bookmarkData = try? url.bookmarkData()
newBook.name = "\(url.lastPathComponent)"
// Save bookmarkURL into CoreData
newBook.urldata = bookmarkData
// Specifiying parent item in CoreData
newBook.origin = playlist.self
try? viewContext.save()
case .failure(let error):
print(error)
}
}
Player retrieving URL:
func Audioplayer(bookmarkData: Data) {
// Restore security scoped bookmark
var bookmarkDataIsStale = false
let playNow = try? URL(resolvingBookmarkData: bookmarkData, bookmarkDataIsStale: &bookmarkDataIsStale)
do {
player = try AVAudioPlayer(contentsOf: playNow!)
// Delegate listen when audio is finished
player?.delegate = del
NotificationCenter.default.addObserver(forName: NSNotification.Name("ended"), object: nil, queue: .main) { (_) in
player?.stop()
ended = true
let _ = print("---- Book has ended ----")
}
} catch let error {
print("Player Error", error.localizedDescription)
}
player?.prepareToPlay()
player?.play()
}
Thank you and again here's repo on git.

audio and video out of sync nextlevel iOS lib

We are using NextLevel iOS video recording library 0.8.4 (https://github.com/nextlevel/NextLevel/) and find that at times we are receiving video that is not synced with the audio. We don't believe its version specific as this issue has cropped up since we built the app in early August 2017.
Currently app is running only on iOS 11. Unfortunately haven't been able to reproduce or narrow down to specific iPhone model. Using Swift version 4.0.
We allow users to create 30 second video captures with both fwd/rear facing cameras. They hold a button to record the video, then when 30 seconds has passed or when they release record button and click a Submit UI button, we then call an export function, similar to this:
func exportVideo() {
guard let session = NextLevel.shared.session else {
return
}
session.mergeClips(usingPreset: AVAssetExportPresetMediumQuality) { [weak self] (url, error) in
self?.hideLoading()
guard let strongSelf = self, let url = url, error == nil else {
self?.showAlert(with: error)
return
}
strongSelf.delegate?.videoCaptureViewController(strongSelf, didSendEvent: .capturedVideo(withURL: url))
}
}

iOS NSURLSession with Wi-Fi Assist turned on results in crashing app

I'm performing an HTTP request using iOS's NSURLSession. My code looks like this:
let session = NSURLSession.sharedSession()
let url = NSURL(string:"www.example.com")
guard let url = url else {
return
}
let request = NSURLRequest(URL: url)
var task = session.dataTaskWithRequest(request){
(data, response, error) -> Void in
//do stuff with the data
}
task.resume()
(sorry if my code isn't 100% correct I just typed it real quickly inside my browser, you get the idea)
When Wi-Fi Assist is turned off it works fine, but when Wi-Fi Assist is turned on the app crashes.
I found this but the discussion never got an answer.
Apart from the fact that I want to fix the problem I am very curious WHY this is happening.

App not working with 3g connection but works fine on wifi

Adhoc deployed app on a device, the app runs fine with wifi, but does not work with 3g connection. Any idea what i'm missing?
Din't get much help from google.
And also the app installed does not show in the Use Mobile Data For : list
Code :
//To handle time out issue with 3g
configuration.timeoutIntervalForResource = 60
// Mark using Alamofire to do the downloads
self.alamofireManager = Alamofire.Manager(configuration:configuration)
self.alamofireManager!.request(.GET, jsonUrl).responseJSON(){
(_, _, JSON, _) in
println("printing json :\(JSON)")
if JSON != nil {
let imageInfos = (JSON!.valueForKey("image") as [NSDictionary]).map {
ImageInfo(id: $0["id"] as String, url: $0["url"] as String)
}
self.tableData.addObjectsFromArray(imageInfos)
}
Error log:
I get a
(Error Domain = NSURLErrorDomain Code = -1004 )
no matter how much i increase the timeoutInterval. Tried both with Resource and Request
Forgot to mention that the server was a Raspberry Pi, and i could not access the server outside the LAN so that was causing the problem. Thanks for the help. timeout was very helpful in handling server faults.
there wan't be any issue with app working on wifi or 3G. the only problem with request timeout. the issue related to internet bandwidth.
Please use following code for change request time out may be help to you.
var alamofireManager : Alamofire.Manager?
func getCallToServer(){
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.timeoutIntervalForResource = 10 // seconds
self.alamofireManager = Alamofire.Manager(configuration: configuration)
self.alamofireManager!.request(.GET, "http://example.com/")
.response { (request, response, data, error) in
}
}

Resources