Platforms to show: All Mac Windows Linux Cross-Platform
/MacFrameworks/NSURLSession Test
Required plugins for this example: MBS MacBase Plugin, MBS MacFrameworks Plugin, MBS Main Plugin, MBS MacControls Plugin
You find this example project in your Plugins Download as a Xojo project file within the examples folder: /MacFrameworks/NSURLSession Test
This example is the version from Mon, 12th Apr 2020.
Project "NSURLSession Test.xojo_binary_project"
Class App Inherits Application
Const kEditClear = "&Delete"
Const kFileQuit = "&Quit"
Const kFileQuitShortcut = ""
End Class
Class MainWindow Inherits Window
Control DownloadButton Inherits PushButton
ControlInstance DownloadButton Inherits PushButton
EventHandler Sub Action()
Dim URL As String = "https://www.monkeybreadsoftware.de/images/MBSLogo.jpg"
Dim d As NSURLSessionDownloadTaskMBS = session.downloadTaskWithURL(URL)
// start it!
d.resume
task = d
End EventHandler
End Control
Control List Inherits Listbox
ControlInstance List Inherits Listbox
End Control
Control UploadButton Inherits PushButton
ControlInstance UploadButton Inherits PushButton
EventHandler Sub Action()
Dim URL As String = "https://www.monkeybreadsoftware.com/filemaker/echo.cgi"
// build a post request
Dim headers As New Dictionary
headers.Value("Test") = "Another header"
Dim r As New NSMutableURLRequestMBS(url)
r.setHTTPMethod "POST"
r.setAllHTTPHeaderFields headers
Dim data As MemoryBlock = "Hello World"
Dim d As NSURLSessionUploadTaskMBS = session.uploadTaskWithRequest(r, data)
// start it!
d.resume
task = d
End EventHandler
End Control
Control StreamButton Inherits PushButton
ControlInstance StreamButton Inherits PushButton
EventHandler Sub Action()
// we do a HTTP request manually
Dim d As NSURLSessionStreamTaskMBS = session.streamTaskWithHostName("www.monkeybreadsoftware.de", 80)
// start it!
d.resume
Dim lines() As String
lines.Append "GET /images/MBSLogo.jpg HTTP/1.0"
lines.Append "User-Agent: Test Example"
lines.Append "Host: www.monkeybreadsoftware.de"
lines.Append ""
lines.Append ""
Dim data As String = Join(lines, EndOfLine.Windows)
d.writeData data, 60, AddressOf streamDataWritten
task = d
End EventHandler
End Control
EventHandler Sub Close()
// optional cancel all tasks
session.invalidateAndCancel
session.list = Nil
End EventHandler
EventHandler Sub Open()
Dim configuration As New NSURLSessionConfigurationMBS
// configure...
configuration.allowsCellularAccess = True
session = New NSURLSession(configuration)
session.list = list
End EventHandler
Sub StreamDataRead(stream as NSURLSessionStreamTaskMBS, data as MemoryBlock, atEOF as Boolean, error as NSErrorMBS, tag as variant)
Log CurrentMethodName
If error <> Nil Then
Log "Error: "+error.LocalizedDescription
Return
End If
// collect data
If data <> Nil Then
Dim d As String = data
StreamData = StreamData + d
End If
If atEOF Then
// done? so let's look for HTTP header and content
Dim divider As String = EndOfLine.Windows+EndOfLine.Windows // between HTTP header and content
Dim pos As Integer = InStr(streamdata, divider)
If pos > 0 Then
Dim PicData As String = MidB(StreamData, pos+LenB(divider))
Dim p As Picture = Picture.FromData(PicData)
If p <> Nil Then
Dim w As New picWindow
w.Backdrop = p
Else
Break
MsgBox "not a picture?"
End If
stream.closeRead
Else
Break
End If
Else
// ask for more data
stream.readData 1024, 1024*1024, 60, AddressOf streamDataRead
End If
End Sub
Sub StreamDataWritten(stream as NSURLSessionStreamTaskMBS, error as NSErrorMBS, tag as variant)
Log CurrentMethodName
If error <> Nil Then
Log "Error: "+error.LocalizedDescription
Else
Log "Request sent."
// let's read some data from result
stream.readData 1024, 1024*1024, 60, AddressOf streamDataRead
// close write channel as we don't need it anymore
stream.closeWrite
End If
End Sub
Sub log(s as string)
list.AddRow s
End Sub
Property StreamData As string
Property session As NSURLSession
Property task As NSURLSessionTaskMBS
End Class
MenuBar MainMenuBar
MenuItem FileMenu = "&File"
MenuItem FileQuit = "#App.kFileQuit"
MenuItem EditMenu = "&Edit"
MenuItem EditUndo = "&Undo"
MenuItem EditSeparator1 = "-"
MenuItem EditCut = "Cu&t"
MenuItem EditCopy = "&Copy"
MenuItem EditPaste = "&Paste"
MenuItem EditClear = "#App.kEditClear"
MenuItem EditSeparator2 = "-"
MenuItem EditSelectAll = "Select &All"
End MenuBar
Class NSURLSession Inherits NSURLSessionMBS
EventHandler Sub dataTaskDidBecomeDownloadTask(dataTask as NSURLSessionDataTaskMBS, downloadTask as NSURLSessionDownloadTaskMBS)
Log CurrentMethodName
End EventHandler
EventHandler Sub dataTaskDidBecomeStreamTask(dataTask as NSURLSessionDataTaskMBS, downloadTask as NSURLSessionStreamTaskMBS)
Log CurrentMethodName
End EventHandler
EventHandler Sub dataTaskDidReceiveData(dataTask as NSURLSessionDataTaskMBS, data as MemoryBlock)
Log CurrentMethodName
End EventHandler
EventHandler Function dataTaskDidReceiveResponse(dataTask as NSURLSessionDataTaskMBS, response as NSURLResponseMBS) As Integer
Log CurrentMethodName
Log "MimeType: "+response.MIMEType
Log "expectedContentLength: "+Str(response.expectedContentLength)
Return Me.ResponseAllow
End EventHandler
EventHandler Function dataTaskWillCacheResponse(dataTask as NSURLSessionDataTaskMBS, proposedResponse as NSCachedURLResponseMBS) As NSCachedURLResponseMBS
Log CurrentMethodName
// allow caching
Return proposedResponse
End EventHandler
EventHandler Sub didBecomeInvalid(error as NSErrorMBS)
Log CurrentMethodName
End EventHandler
EventHandler Sub didReceiveChallenge(challenge as NSURLAuthenticationChallengeMBS, byref disposition as Integer, byref credential as NSURLCredentialMBS)
Log CurrentMethodName
// here you could provide password or check SSL certificates
End EventHandler
EventHandler Sub downloadTaskDidFinishDownloadingToURL(downloadTask as NSURLSessionDownloadTaskMBS, location as String, file as FolderItem)
Log CurrentMethodName
Log "location: "+location
If file <> Nil Then
Dim p As Picture = Picture.Open(file)
If p <> Nil Then
Dim w As New picWindow
w.backdrop = p
w.Title = downloadTask.response.suggestedFilename
End If
End If
End EventHandler
EventHandler Sub downloadTaskDidResumeAtOffset(downloadTask as NSURLSessionDownloadTaskMBS, fileOffset as Int64, expectedTotalBytes as Int64)
Log CurrentMethodName
End EventHandler
EventHandler Sub downloadTaskDidWriteData(downloadTask as NSURLSessionDownloadTaskMBS, bytesWritten as Int64, totalBytesWritten as Int64, totalBytesExpectedToWrite as Int64)
Log CurrentMethodName+" "+Str(bytesWritten)+" or "+Str(totalBytesExpectedToWrite)
End EventHandler
EventHandler Sub streamTaskReadClosedForStreamTask(streamTask as NSURLSessionStreamTaskMBS)
Log CurrentMethodName
End EventHandler
EventHandler Sub streamTaskWriteClosedForStreamTask(streamTask as NSURLSessionStreamTaskMBS)
Log CurrentMethodName
End EventHandler
EventHandler Sub taskDidCompleteWithError(task as NSURLSessionTaskMBS, error as NSErrorMBS)
Log CurrentMethodName
End EventHandler
EventHandler Sub taskDidFinishCollectingMetrics(task as NSURLSessionTaskMBS, metrics as NSURLSessionTaskMetricsMBS)
Log CurrentMethodName
Log "redirectCount: "+Str(metrics.redirectCount)
Dim transactionMetrics() As NSURLSessionTaskTransactionMetricsMBS = metrics.transactionMetrics
For Each transactionMetric As NSURLSessionTaskTransactionMetricsMBS In transactionMetrics
'Log "remoteAddress: " + transactionMetric.remoteAddress
'Log "remotePort: " + Str(transactionMetric.remotePort)
Log "networkProtocolName: " + transactionMetric.networkProtocolName
Next
End EventHandler
EventHandler Sub taskDidSendBodyData(task as NSURLSessionTaskMBS, bytesSent as Int64, totalBytesSent as Int64, totalBytesExpectedToSend as Integer)
Log CurrentMethodName
End EventHandler
EventHandler Sub taskIsWaitingForConnectivity(task as NSURLSessionTaskMBS)
Log CurrentMethodName
End EventHandler
EventHandler Function taskWillPerformHTTPRedirection(task as NSURLSessionTaskMBS, response as NSURLResponseMBS, request as NSURLRequestMBS) As NSURLRequestMBS
Log CurrentMethodName
log "URL: "+request.URL
Return request
End EventHandler
Sub log(s as string)
list.AddRow s
End Sub
Property StreamInputStream As NSInputStreamMBS
Property StreamOutputStream As NSOutputStreamMBS
Property list As listbox
End Class
Class picWindow Inherits Window
End Class
End Project
The items on this page are in the following plugins: MBS MacFrameworks Plugin.