I have a critical issue where my websocket will not connect to a server that is sitting behind an NGINX reverse proxy only on iOS 13. I have tested on both a real device and simulator with no success. It simply hangs on preparing. it never receives updates to the viabilityUpdateHandler and only ever enters the preparing state of the stateUpdateHandler. On any iOS greater or equal to iOS 14 it works seamlessly. I can connect to a local server that is not dealing with any certificates on iOS 13 no problem, but when my production server is in play it does not communicate something properly.
I am using NWConnection's NWProtocolWebSocket.
The setup is basic and straight forward
let options = NWProtocolWebSocket.Options()
options.autoReplyPing = configuration.autoReplyPing
options.maximumMessageSize = configuration.maximumMessageSize
if configuration.urlRequest != nil {
options.setAdditionalHeaders(configuration.urlRequest?.allHTTPHeaderFields?.map { ($0.key, $0.value) } ?? [])
_ = configuration.cookies.map { cookie in
options.setAdditionalHeaders([(name: cookie.name, value: cookie.value)])
}
}
if !configuration.headers.isEmpty {
options.setAdditionalHeaders(configuration.headers.map { ($0.key, $0.value) } )
}
let parameters: NWParameters = configuration.trustAll ? try TLSConfiguration.trustSelfSigned(
configuration.trustAll,
queue: configuration.queue,
certificates: configuration.certificates) : (configuration.url.scheme == "ws" ? .tcp : .tls)
parameters.defaultProtocolStack.applicationProtocols.insert(options, at: 0)
connection = NWConnection(to: .url(configuration.url), using: parameters)
The trust store is also straight forward
public static func trustSelfSigned(_
trustAll: Bool,
queue: DispatchQueue,
certificates: [String]?
) throws -> NWParameters {
let options = NWProtocolTLS.Options()
var secTrustRoots: [SecCertificate]?
secTrustRoots = try certificates?.compactMap({ certificate in
let filePath = Bundle.main.path(forResource: certificate, ofType: "der")!
let data = try Data(contentsOf: URL(fileURLWithPath: filePath))
return SecCertificateCreateWithData(nil, data as CFData)!
})
sec_protocol_options_set_verify_block(
options.securityProtocolOptions,
{ _, sec_trust, sec_protocol_verify_complete in
guard !trustAll else {
sec_protocol_verify_complete(true)
return
}
let trust = sec_trust_copy_ref(sec_trust).takeRetainedValue()
if let trustRootCertificates = secTrustRoots {
SecTrustSetAnchorCertificates(trust, trustRootCertificates as CFArray)
}
dispatchPrecondition(condition: .onQueue(queue))
SecTrustEvaluateAsyncWithError(trust, queue) { _, result, error in
if let error = error {
print("Trust failed: \(error.localizedDescription)")
}
print("Validation Result: \(result)")
sec_protocol_verify_complete(result)
}
},
queue
)
sec_protocol_options_set_min_tls_protocol_version(options.securityProtocolOptions, .TLSv12)
let parameters = NWParameters(tls: options)
parameters.allowLocalEndpointReuse = true
parameters.includePeerToPeer = true
return parameters
}
Post
Replies
Boosts
Views
Activity
I am creating a memo app for iOS with Swift + Core Data.
I want to back up and restore Core Data contents while preserving relationships.
but, I don't know how to do that.
Could you tell me how to backup and restore the relationship while maintaining it?
Thank you.
I have a function that queries an SQLite database and returns names, dates and values. In SQLite the dates are in Julian format. I convert the dates in the SQLite query to a date time string which give me "2022-08-01 00:00:00". I want to display this date as the date string "Aug 1, 2022". The only way I have been able to achieve this is to convert the first date string to a date via a date formatter then convert this date to the desired date string via a second date formatter. Is there a more direct way to do this?
func AccessSQLiteDB(db: OpaquePointer?) {
let queryTradingDaysStatement = """
WITH
TempTable1
AS
(
SELECT
max(TimeStamp) - 365.25 as StartingDate
FROM
TradingDays
WHERE
FundName = 'Fund1'
),
TempTable2
AS
(
SELECT
main.FundName,
datetime(main.TimeStamp) as SQLDateString,
main.Close
FROM
TradingDays main, TempTable1 as temp
WHERE
main.FundName = 'Fund1'
AND
main.TimeStamp >= temp.StartingDate
)
SELECT
FundName,
SQLDateString,
Close
FROM
TempTable2
ORDER By
SQLDateString ASC
;
"""
let sqlDateStringFormatter = DateFormatter()
sqlDateStringFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
sqlDateStringFormatter.timeZone = .gmt
var queryTradingDaysCPtr: OpaquePointer?
if sqlite3_prepare_v2(db, queryTradingDaysStatement, -1, &queryTradingDaysCPtr, nil) == SQLITE_OK {
while (sqlite3_step(queryTradingDaysCPtr) == SQLITE_ROW) {
let fundName = sqlite3_column_text(queryTradingDaysCPtr, 0)
let timeStamp = sqlite3_column_text(queryTradingDaysCPtr, 1)
let close = sqlite3_column_double(queryTradingDaysCPtr, 2)
let fundNameAsString = String(cString: fundName!)
let timeStampAsString = String(cString: timeStamp!)
print(timeStampAsString) // returns this format 2022-08-01 00:00:00
let timeStampAsDate: Date = sqlDateStringFormatter.date(from: timeStampAsString)!
print("\(timeStampAsDate)") // returns this format 2022-08-01 00:00:00 +0000
let mediumDataFormatter = DateFormatter()
mediumDataFormatter.dateStyle = .medium
mediumDataFormatter.timeZone = .gmt
let dateString = mediumDataFormatter.string(from: timeStampAsDate)
print(dateString) // returns this format Aug 1, 2022
let closeAsString = String(format: "$%.2f", close)
print(fundNameAsString + " - " + dateString + " - " + closeAsString)
} // end while loop
} else {
let errorMessage = String(cString: sqlite3_errmsg(db))
print("\nQuery is not prepared \(errorMessage)")
}
sqlite3_finalize(queryTradingDaysCPtr)
}
Im getting a scoping error in the default App.swift file of my Xcode project and ive done everything to try to solve the issue, my ContentView struct is at the top level, ive cleaned the build folder a hundred times, restarted Xcode, cleared the derived data folder for nothing to happen. Here is my ContentView.swift file below.
protocol runPyAndSendRequestRunnable {
func runPyServer() -> String
func sendRequest(inputText: String, completion: @escaping(String) -> Void)
}
func runPyServer() -> String {
print("server run")
return "server run"
}
func sendRequest() -> String {
print("request sent")
return "request sent"
}
struct MyPyType: runPyAndSendRequestRunnable {
func runPyServer() -> String {
return "server started"
}
func sendRequest(inputText: String,completion: @escaping(String) ->Void) {
let userInput = inputText
guard let url = URL(string:"http://localhost:8080/MacGPT") else {
completion("Error: failed to obtain url")
return
}
}
struct ContentView: View {
var viewController: runPyAndSendRequestRunnable? = MyPyType()
@State private var text: String = ""
@State private var filePath = ""
@State private var inputText = ""
var body: some View {
makeContent()
.onAppear{
NSApp.mainWindow?.makeFirstResponder(NSApp.mainWindow?.contentView)
}
}
func makeContent() -> some View {
ScrollView {
HStack {
VStack {
VStack(alignment: .center, spacing: 200) {
makeGlobeImage()
makeSecondLogo()
makeTitle()
makeSubtitle()
makeTextFieldAndEnter()
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
.frame(maxWidth: .infinity)
}
}
.background(Color.white.opacity(0.9))
.cornerRadius(12)
.padding(.horizontal, 57)
.padding(.bottom, 80)
.frame(minWidth: 1600, minHeight: 1050)
.background(Color.white.opacity(0.1))
.cornerRadius(12)
}
func makeGlobeImage() -> some View {
Image(systemName: "globe")
.foregroundColor(.blue)
.font(.system(size: 40))
.offset(y: 348)
.offset(x: -240)
}
func makeSecondLogo() -> some View {
Image("second Logo")
.resizable()
.scaledToFit()
.frame(width: 90, height: 90)
.offset(x: 185)
.offset(y: 78)
}
func makeTitle() -> some View {
Text("Mac GPT")
.font(Font.custom("Futura", size: 77))
.foregroundColor(Color.black)
.padding(2.15)
.overlay(RoundedRectangle(cornerRadius: 20).stroke(Color.gray, lineWidth: 1.0))
.offset(x: -37)
.offset(y: -221)
}
func makeSubtitle() -> some View {
VStack {
Spacer()
Text("Access the power of AI right from your Mac's homescreen, just for Mac.")
.font(Font.custom("Futura", size: 18.6))
.fontWeight(.bold)
.padding(.vertical, 11)
}
.offset(y: -20)
.offset(x: -40)
}
func makeTextFieldAndEnter() -> some View {
ZStack {
Spacer()
TextField("Ask Mac GPT...", text: $inputText, onCommit: {
executeProcess(withInput: inputText) { response in
print(response)
}
})
.font(Font.custom("Futura", size: 17.4))
.padding(.horizontal, 25)
.padding(.vertical, 15)
.background(Color.white)
.cornerRadius(29)
.overlay(
RoundedRectangle(cornerRadius: 27.9).stroke(Color.gray, lineWidth: 1.0)
)
.offset(y: -200)
.padding(.horizontal, 35)
}
}
func executeProcess(withInput input: String, completion: @escaping (String) -> Void ) {
DispatchQueue.global().async {
DispatchQueue.main.async {
guard !input.isEmpty else {
print("TextField is empty, enter input in the text field")
return
}
self.viewController?.runPyServer() // add closures
self.viewController?.sendRequest(inputText: input) { response in
completion(response)
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
}
}
-code`
I've implemented a PacketTunnelProvider for iOS. When I set an IPv4 address as the tunnel's DNS server, everything works as expected: all DNS queries from the device are sent through the tunnel. However, when I try to use an IPv6 address, no queries are sent (in fact, no IPv6 packets are sent at all) and the device is unable to resolve domain names.
Here's the relevant code:
let settings = NEPacketTunnelNetworkSettings(tunnelRemoteAddress: "1.2.3.4")
let settings4 = NEIPv4Settings(addresses: ["192.128.1.2"], subnetMasks: ["255.255.255.255"])
settings4.includedRoutes = [NEIPv4Route.default()]
settings4.excludedRoutes = []
settings.ipv4Settings = settings4
let settings6 = NEIPv6Settings(addresses: ["2001:4860:123:456::"], networkPrefixLengths: [64])
settings6.includedRoutes = [NEIPv6Route.default()]
settings6.excludedRoutes = []
settings.ipv6Settings = settings6
// If I use this DNS server, everything works normally
//let dnsSettings = NEDNSSettings.init(servers: ["8.8.8.8"])
// With this DNS server, no DNS queries are sent through the tunnel
let dnsSettings = NEDNSSettings.init(servers: ["2001:4860:4860::8888"])
dnsSettings.matchDomains = [""]
settings.dnsSettings = dnsSettings
In the application iCloud integration but in the container, it displays the name of the bundle that owns the container.
Configuration iCloud capability from developer account
Enable iCloud capability from Xcode
Added keys and value into info.plist file as below
<key>NSUbiquitousContainers</key>
<dict>
<key>iCloud.com.example.applepaydemo</key>
<dict>
<key>NSUbiquitousContainerName</key>
<string>Apple Demo</string>
<key>NSUbiquitousContainerIsDocumentScopePublic</key>
<true/>
<key>NSUbiquitousContainerSupportedFolderLevels</key>
<string>Any</string>
</dict>
</dict>
Issue: It displays applepaydemo name of container not Apple Demo in iCloud Manage Account Storage
I am wondering why Xcode uses CPU for Metal GPU shader program execution for Swift. With Objective-C Metal, it finishes instantly. But the same shader program, when called from Swift, takes many seconds. GPU is idle while CPU runs 99%. I use the following line to choose GPU in Swift. But doesn't seem to choose real GPU.
let device: MTLDevice = MTLCreateSystemDefaultDevice()!
For Objective-C, I use the same default device. This chooses GPU correctly.
MTLDevice device = MTLCreateSystemDefaultDevice();
Is there any way I can choose GPU in Swift Metal?
Can Flutter project be built on Existing iOS Swift Native project using platform channels?
the swift project is related to travelling and location -maps, Driver's live location.. etc
Can a flutter project be created on top of that to access all functionalities by using platform channels ?
the xcode will freze for 3mins when hit a breakpoint. it report "Fetching variables on ***'s iPhone"
it happens when hit a new breakpoint, and the xcode will freeze for 3mins, then it will be ok. anysolution? its wasting my time.
the xcode continue print the log below:
(arm64) /Users/xx/Desktop/patch/Project/Pods/TestSDK/vendor/***.framework/***(FPEncryptMsg.pb-c.o) 0x00000c22: unable to locate module needed for external types: /Users/packagedevice/Library/Developer/Xcode/DerivedData/ModuleCache.noindex/38MC9CUKFC6LS/Darwin-MI6WZSG1PNOM.pcm
error: '/Users/packagedevice/Library/Developer/Xcode/DerivedData/ModuleCache.noindex/38MC9CUKFC6LS/Darwin-MI6WZSG1PNOM.pcm' does not exist
Debugging will be degraded due to missing types. Rebuilding the project will regenerate the needed module files.
Our project has many dependencies which are binary file. And these dependencies are build in the remote serve。Anyone has ideas about this
I am working with data in Swift using the TabularData framework. I load data from a CSV file into a DataFrame, then copy the data into a second DataFrame, and finally remove a row from the second DataFrame.
The problem arises when I try to remove a row from the second DataFrame, at which point I receive an EXC_BAD_ACCESS error. However, if I modify the "timings" column (the final column) before removing the row (even to an identical value), the code runs without errors.
Interestingly, this issue only occurs when a row in the column of the CSV file contains more than 15 characters.
This is the code I'm using:
func loadCSV() {
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let url = documentsDirectory.appendingPathComponent("example.csv")
var dataframe: DataFrame
do {
dataframe = try .init(
contentsOfCSVFile: url,
columns: ["user", "filename", "syllable count", "timings"],
types: ["user": .string, "filename": .string, "syllable count": .integer, "timings": .string]
)
} catch {
fatalError("Failed to load csv data")
}
print("First data frame",dataframe, separator: "\n") /// This works
var secondFrame = DataFrame()
secondFrame.append(column: Column<String>(name: "user", capacity: 1000))
secondFrame.append(column: Column<String>(name: "filename", capacity: 1000))
secondFrame.append(column: Column<Int>(name: "syllable count", capacity: 1000))
secondFrame.append(column: Column<String>(name: "timings", capacity: 1000))
for row in 0..<dataframe.rows.count {
secondFrame.appendEmptyRow()
for col in 0..<4 {
secondFrame.rows[row][col] = dataframe.rows[row][col]
}
}
// secondFrame.rows[row][3, String.self] = String("0123456789ABCDEF") /* If we include this line, it will not crash, even though the content is the same */
print("Second data frame before removing row",dataframe, separator: "\n") // Before removal
secondFrame.removeRow(at: 0)
print("Second data frame after removing row",dataframe, separator: "\n") // After removal—we will get Thread 1: EXC_BAD_ACCESS here. The line will still print, however
}
and the csv (minimal example):
user,filename,syllable count,timings
john,john-001,12,0123456789ABCDEF
jane,jane-001,10,0123456789ABCDE
I've been able to replicate this bug on macOS and iOS using minimal projects. I'm unsure why this error is occurring and why modifying the "timings" column prevents it.
It should be noted that this same error occurs with a single data frame loaded from a CSV file, which means that I basically cannot load from CSV if I want to modify the DataFrame afterwards.
Can I get some help on this? I believe my struct that I am using is in scope but Xcode is saying otherwise.
Project: React-Native project w/ Swift
X-Code Version: 14.3.1
Error: "Cannot find 'SessionWidgetAttributes' in scope"
File/Class: LiveActivity.swift
Problem: Whenever I turn on "Show live issues" the error goes away. When I type in code in LiveActivity.swift Xcode recognizes the struct I am accessing. The error is only thrown when I build. After building the error goes away. It seems like Xcode recognizes the struct when I am coding but when I build it errors out.
Could this be due to some build setting? I have added LiveActivity.swift to my two targets: TestProject and SessionWidgetExtension
The struct I am accessing is in the SessionWidgetExtension target.
Screen Shots: https://imgur.com/a/hHPWJwE
Any thoughts?
In my Xcode I have created a Product.StoreKit and within that I have a subscription with which has 3 Offer Codes.
In PaymentView I am trying to open a Redemption Sheet as follows:
if #available(iOS 14.0, *) {
paymentQueue.presentCodeRedemptionSheet()
}
But the Redemption Sheet is Pre-populated with Offer Codes and instead of having a text field to enter Offer Code, user can simply choose from the list of offer codes.
I am building my macOS app for distribution outside the Mac App store using a shell script as shown below. When a user reports a crash, all I get is offsets and I can’t tell what is going on, where:
Thread 3 Crashed:
0 Meteorologist 0x1026da778 0x10268c000 + 321400
1 Meteorologist 0x1026d6354 0x10268c000 + 303956
2 Meteorologist 0x1026d0a8c 0x10268c000 + 281228
3 Meteorologist 0x1026e8ae4 0x10268c000 + 379620
4 Meteorologist 0x1026f7501 0x10268c000 + 439553
5 Meteorologist 0x1026f6621 0x10268c000 + 435745
6 Meteorologist 0x1026f74f9 0x10268c000 + 439545
7 Meteorologist 0x1026f7509 0x10268c000 + 439561
If I understand correctly, I need to include a dSYM file in my executable. I have DWARF with dSYM File in my Build Options, Release value.
I can see the dSYM in my .xcarchive file. How do I get it into my .app executable? I do include uploadSymbols=TRUE in my exportOptionsPlist file.
If I manually copy the dSYM file, prior to the notarytool step, notarytool throws an error. If I insert the dSYM file after I notarize then it gets flagged when I open the app because it doesn't match what was notarized.
#!/bin/bash
#set -e
#set -x
TEMPLATE_DMG=dist/template.dmg
# "working copy" names for the intermediate dmgs
WC_DMG=wc.dmg
WC_DIR=/Volumes/Meteorologist
VERSION=`cat ../website/VERSION2`
SOURCE_FILES="./Build/Release/Meteorologist.app ./dist/Readme.rtf"
MASTER_DMG="./Build/Meteorologist-${VERSION}.dmg"
# .altoolid = abc@icloud.com aka Developer Email
# .altoolpw = abcd-efgh-ijkl-mnop aka App-specific password
# .altooltm = ABCD123456 aka Team ID
dev_account=$(cat ~/.altoolid)
dev_passwd=$(cat ~/.altoolpw)
dev_teamid=$(cat ~/.altooltm)
mkdir ./Build
rm -rf ./Build/*
echo
echo ........................
echo "------------------------ Storing Credentials -----------------------"
echo xcrun notarytool store-credentials --apple-id \"$dev_account\" --team-id \"$dev_teamid\" --password \"$dev_passwd\" notary-scriptingosx
xcrun notarytool store-credentials --apple-id "$dev_account" --team-id="$dev_teamid" --password "$dev_passwd" notary-scriptingosx > xcodebuild.log
exit_status=$?
if [ "${exit_status}" != "0" ]
then
cat xcodebuild.log
exit 1
fi
rm xcodebuild.log
echo
echo ........................
echo "------------------------ Building Project as an Archive -----------------------"
echo xcodebuild -project Meteorologist.xcodeproj -scheme Meteorologist -configuration Release -derivedDataPath ./Build -allowProvisioningUpdates --options=runtime clean archive -archivePath ./Build/Meteorologist.xcarchive
xcodebuild -project Meteorologist.xcodeproj -scheme Meteorologist -configuration Release -derivedDataPath ./Build -allowProvisioningUpdates --options=runtime clean archive -archivePath ./Build/Meteorologist.xcarchive > xcodebuild.log
exit_status=$?
if [ "${exit_status}" != "0" ]
then
cat xcodebuild.log
exit 1
fi
rm xcodebuild.log
echo
echo ........................
echo "------------------------ Creating exportOptions.plist -----------------------"
echo \<?xml version=\"1.0\" encoding=\"UTF-8\"?\> > exportOptions.plist
echo \<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\"\> >> exportOptions.plist
echo \<plist version=\"1.0\"\> >> exportOptions.plist
echo \<dict\> >> exportOptions.plist
echo \<key\>destination\</key\> >> exportOptions.plist
echo \<string\>export\</string\> >> exportOptions.plist
echo \<key\>signingStyle\</key\> >> exportOptions.plist
echo \<string\>automatic\</string\> >> exportOptions.plist
echo \<key\>method\</key\> >> exportOptions.plist
echo \<string\>developer-id\</string\> >> exportOptions.plist
echo \<key\>uploadSymbols\</key\> >> exportOptions.plist
echo \<true/\> >> exportOptions.plist
echo \</dict\> >> exportOptions.plist
echo \</plist\> >> exportOptions.plist
echo
echo ........................
echo "------------------------ Exporting the Archive -----------------------"
echo xcodebuild -exportArchive -archivePath ./Build/Meteorologist.xcarchive -exportOptionsPlist exportOptions.plist -exportPath ./Build/Release
xcodebuild -exportArchive -archivePath ./Build/Meteorologist.xcarchive -exportOptionsPlist exportOptions.plist -exportPath ./Build/Release > xcodebuild.log
exit_status=$?
if [ "${exit_status}" != "0" ]
then
cat xcodebuild.log
exit 1
fi
rm xcodebuild.log
echo
echo ........................
echo "------------------------ Compressing the app -----------------------"
echo /usr/bin/ditto -c -k --keepParent ./Build/Release/Meteorologist.app ./Build/Release/Meteorologist.zip
/usr/bin/ditto -c -k --keepParent ./Build/Release/Meteorologist.app ./Build/Release/Meteorologist.zip
if [ "${exit_status}" != "0" ]
then
echo "Compress (ditto) failed"
exit 1
fi
echo
echo ........................
echo "------------------------ Notarizing the app -----------------------"
echo xcrun notarytool submit ./Build/Release/Meteorologist.zip --keychain-profile=notary-scriptingosx --wait
xcrun notarytool submit ./Build/Release/Meteorologist.zip --keychain-profile=notary-scriptingosx --wait
if [ "${exit_status}" != "0" ]
then
echo "xcrun notarytool failed"
exit 1
fi
echo
echo ........................
echo "------------------------ Stapling the app -----------------------"
echo xcrun stapler staple "./Build/Release/Meteorologist.app"
xcrun stapler staple "./Build/Release/Meteorologist.app"
if [ "${exit_status}" != "0" ]
then
echo "xcrun stapler failed"
exit 1
fi
echo
rm ./Build/Release/Meteorologist.zip
I am sure this is an elementary question, but I am new to Swift and Metal, but have a fair amount of experience using Objective C and OpenGL.
I would like to render some mathematically generated surfaces in Metal and need to fill the vertex buffer with positions and normals. I would guess that creating a one dimensional array and adding to it using "append" is not the most efficient way to do this. The buffer might be quite large and I would like to set aside the memory for it in advance, which is how I did it using Objective C. Can anyone suggest the best way to do this? Thanks in advance.
Consider this simple regex that is supposed to match anything but a semicolon:
import RegexBuilder
let regex = /[^;]/
if let match = "a".firstMatch(of: regex) {
print("\(match.output)")
}
As expected, running this prints "a". When I use the context menu action Refactor > Convert to Regex Builder, Xcode converts the above code into the following:
import RegexBuilder
let regex = Regex {
One(.anyOf(";"))
.inverted
}
if let match = "a".firstMatch(of: regex) {
print("\(match.output)")
}
This will not compile and gives the compiler error
Value of type 'One<CharacterClass.RegexOutput>' (aka 'One') has no member 'inverted'
How can this RegexBuilder expression be fixed? I am mainly asking this because I would like to use the inverted function in a more complex example, but so far have been unable to make it work.
Hello,
I need help reading the data from my MySQL database.
I would like to have the data read out in a loop and later add it to the NavigationView > List.
Can someone point out my mistakes here?
Or am I on the wrong track here?
Or is there another way to read data from a database?
I have an API file on my server (no Localhost)
<?php
// Create connection
$con=mysqli_connect("my-mysql-domain.com","usernmae","password","database");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// This SQL statement selects ALL from the table 'Locations'
$sql = "SELECT * FROM Tablename";
// Check if there are results
if ($result = mysqli_query($con, $sql))
{
// If so, then create a results array and a temporary one
// to hold the data
$resultArray = array();
$tempArray = array();
// Loop through each row in the result set
while($row = $result->fetch_object())
{
// Add each row into our results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
// Finally, encode the array to JSON and output the results
echo json_encode($resultArray);
}
// Close connections
mysqli_close($con);
?>
my php gives me the following output:
[{"id":"1","nachname":"Tester Name","vorname":"Tester Vorname","nummer":"123","mail":"muster@meinedomain.de","adresse":"Musterstrasse","plz":"12345","ort":"Ortname","title":"Beispieltitle","post":"Hier der Inhalt"},{"id":"2","nachname":"Smith","vorname":"Jin","nummer":"567","mail":"no mail","adresse":"Street","plz":"12345","ort":"Berlin","title":"","post":""}]
now to the Swift:
Swift-File StockModel.swift
import UIKit
import SwiftUI
class StockModel: NSObject, ObservableObject {
//properties of a stock
var id: String?
var nachname: String?
var vorname: String?
var nummer: String?
var mail: String?
var adresse: String?
var plz: String?
var ort: String?
var title: String?
var post: String?
//empty constructor
override init()
{
}
//construct with @nachname and @vorname parameters
init(id: String, nachname: String, vorname: String, nummer: String, mail: String, adresse: String, plz: String, ort: String, title: String, post: String) {
self.id = id
self.nachname = nachname
self.vorname = vorname
self.nummer = nummer
self.mail = mail
self.adresse = adresse
self.plz = plz
self.ort = ort
self.title = title
self.post = post
}
//prints a stock's name and price
override var description: String {
return "Nachname: \(String(describing: nachname)), Vorname: \(String(describing: vorname))"
}
}
Swift-File FeedModel.swift
import UIKit
import SwiftUI
/*
protocol FeedModelProtocol: class {
func itemsDownloaded(items: NSArray)
}
*/
protocol FeedModelProtocol: AnyObject {
func itemsDownloaded(items: NSArray)
}
class FeedModel: NSObject, URLSessionDataDelegate, ObservableObject {
@Published var fcdmember: [StockModel] = []
weak var delegate: FeedModelProtocol!
let urlPath = "https://my-domain.com/api/stock_service.php"
func downloadItems() {
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("Error")
}else {
print("stocks downloaded")
//self.parseJSON(data!)
parseJSON(data!)
}
}
task.resume()
}
}
func parseJSON(_ data:Data) {
var jsonResult = NSArray()
do{
jsonResult = try JSONSerialization.jsonObject(with: data, options:JSONSerialization.ReadingOptions.allowFragments) as! NSArray
} catch let error as NSError {
print(error)
}
var jsonElement = NSDictionary()
let stocks = NSMutableArray()
for i in 0 ..< jsonResult.count {
jsonElement = jsonResult[i] as! NSDictionary
let stock = StockModel() //the following insures none of the JsonElement values are nil through optional binding if let name = jsonElement["name"] as? String, let price = jsonElement["price"] as? String { print(name) print(price) stock.name = name stock.price = price } stocks.add(stock) } DispatchQueue.main.async(execute: { () -> Void in
//the following insures none of the JsonElement values are nil through optional binding
if let id = jsonElement["id"] as? String,
let nachname = jsonElement["nachname"] as? String,
let vorname = jsonElement["vorname"] as? String,
let nummer = jsonElement["nummer"] as? String,
let mail = jsonElement["mail"] as? String,
let adresse = jsonElement["adresse"] as? String,
let plz = jsonElement["plz"] as? String,
let ort = jsonElement["ort"] as? String,
let title = jsonElement["title"] as? String,
let post = jsonElement["post"] as? String
{
stock.id = id
stock.nachname = nachname
stock.vorname = vorname
stock.nummer = nummer
stock.mail = mail
stock.adresse = adresse
stock.plz = plz
stock.ort = ort
stock.title = title
stock.post = post
}
stocks.add(stock)
}
DispatchQueue.main.async(execute: { () -> Void in
//self.delegate.itemsDownloaded(items: stocks)
})
}
Swift-File ContentView.swift
import UIKit
import Foundation
struct ContentView: View {
@State private var ausgabe = StockModel()
var body: some View {
VStack {
ForEach(ausgabe, id: \.self) { item in
Text("Your name is \(ausgabe).")
}
}
.padding()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Is there a way to catch the crashes from both swift and obj-c without using any 3rd party libraries?
I want a way to note that my app has crashed, no stack trace needed just want some count of crashes stored to user defaults.
I saw NSSetUncaughtExceptionHandler being used but it is only catching obj-c related errors.
eg. force unwrapping nil is not caught here.
I want a universal way of catching the crashes. also want to know if this can affect the crash reporting by 3rd party libraries
Hello, i am working on my project for the Swift Student Challenge and it came to my attention that the project must be built using Swift Playgrounds. I have run into an issue where I want to add multiple views to my project but it seems i am unable. How am i supposed to do this?
I am learning SQLite queries. I use prepare statement and one or more calls to a step statement. The prepare statement knows the pointer to the database, the UFT8 select statement and the name of the pointer which will point to the complied SQL select statement. The first step call runs the compiled select statement and if data is returned, the first row is made available via column calls. It seems logical to me that the select statement returns all matching rows but if the first step statement only has access to the first row of data, the balance of matching rows must be stored somewhere. Is this the case and if so where are the query results stored? Or is does this work in some other manner?
I am, at least, per success of the operation able to store a username and password in the keychain using the "addUser" function in the code below. I then when doing a login call the "authenticateUser" function but I get a -25300 error (errSecItemNotFound). I'm close here but missing something. Any help would be appreciated.
class func addUser(username: String, password: String) -> Bool {
let serviceName = AppValues.appName // Replace this with a unique identifier for your app
let account = username.data(using: .utf8)!
let passwordData = password.data(using: .utf8)!
let query: [CFString: Any] = [
kSecClass: kSecClassGenericPassword,
kSecAttrService: serviceName,
kSecAttrAccount: account,
kSecValueData: passwordData,
kSecAttrAccessible: kSecAttrAccessibleWhenUnlockedThisDeviceOnly
]
// Delete any existing items with the same account before adding the new one
SecItemDelete(query as CFDictionary)
let status = SecItemAdd(query as CFDictionary, nil)
guard status == errSecSuccess else {
evaluateKeychainError(errorCode: status)
return false
}
LogEvent.print(module: "Authentication.keychain.addUser", message: "\(username)/\(password) added successfully.")
return true
}
class func authenticateUser(username: String, password: String) -> Bool {
let usernameData = username.data(using: .utf8)!
let query: [String: Any] = [
kSecClass as String: kSecClassInternetPassword,
kSecAttrServer as String: AppValues.appName, // Replace with your server or app identifier
kSecAttrAccount as String: usernameData,
kSecReturnData as String: true,
kSecMatchLimit as String: kSecMatchLimitOne
]
var result: AnyObject?
let status = SecItemCopyMatching(query as CFDictionary, &result)
if status == errSecSuccess,
let passwordData = result as? Data,
let retrievedPassword = String(data: passwordData, encoding: .utf8) {
LogEvent.print(module: "Authentication.keychain.authenticateUser", message: "\(username)/\(password)/\(retrievedPassword) authenticated successfully.")
return retrievedPassword == password
} else {
LogEvent.print(module: "Authentication.keychain.authenticateUser", message: "Error \(status)")
evaluateKeychainError(errorCode: status)
return false
}
}