before_code stringlengths 14 465k | reviewer_comment stringlengths 16 64.5k | after_code stringlengths 9 467k | diff_context stringlengths 0 97k | file_path stringlengths 5 226 | comment_line int32 0 26 | language stringclasses 37 values | quality_score float32 0.07 1 | comment_type stringclasses 9 values | comment_length int32 16 64.5k | before_lines int32 1 17.2k | after_lines int32 1 12.1k | is_negative bool 2 classes | pr_title stringlengths 1 308 | pr_number int32 1 299k | repo_name stringclasses 533 values | repo_stars int64 321 419k | repo_language stringclasses 27 values | reviewer_username stringlengths 0 39 | author_username stringlengths 2 39 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
if (propertyType == "String" || propertyType == "Choice" ||
propertyType == "Color" || propertyType == "Behavior" ||
propertyType == "Resource" || propertyType == "LeaderboardId") {
element.SetStringValue(property->GetValue());
} else if (propertyType == "Number") {
element.SetDoubleValue(property->GetValue().To<double>());
} else if (propertyType == "Boolean") {
element.SetBoolValue(property->GetValue() == "true");
}
}
}
std::map<gd::String, gd::PropertyDescriptor> CustomConfigurationHelper::GetProperties(
const gd::PropertiesContainer &properties,
const gd::SerializerElement &configurationContent) {
auto objectProperties = std::map<gd::String, gd::PropertyDescriptor>();
for (auto &property : properties.GetInternalVector()) {
const auto &propertyName = property->GetName();
const auto &propertyType = property->GetType();
// Copy the property
objectProperties[propertyName] = *property;
auto &newProperty = objectProperties[propertyName];
if (configurationContent.HasChild(propertyName)) {
if (propertyType == "String" || propertyType == "Choice" ||
propertyType == "Color" || propertyType == "Behavior" ||
propertyType == "Resource" || propertyType == "LeaderboardId" ||
propertyType == "AnimationName") {
newProperty.SetValue(
configurationContent.GetChild(propertyName).GetStringValue());
} else if (propertyType == "Number") {
newProperty.SetValue(gd::String::From(
configurationContent.GetChild(propertyName).GetDoubleValue()));
} else if (propertyType == "Boolean") {
newProperty.SetValue(
configurationContent.GetChild(propertyName).GetBoolValue()
? "true"
: "false");
}
} else {
// No value was serialized for this property. `newProperty`
// will have the default value coming from `enumeratedProperty`.
}
}
return objectProperties;
}
| No issues found. | if (propertyType == "String" || propertyType == "Choice" ||
propertyType == "Color" || propertyType == "Behavior" ||
propertyType == "Resource" || propertyType == "LeaderboardId") {
element.SetStringValue(property->GetValue());
} else if (propertyType == "Number") {
element.SetDoubleValue(property->GetValue().To<double>());
} else if (propertyType == "Boolean") {
element.SetBoolValue(property->GetValue() == "true");
}
}
}
std::map<gd::String, gd::PropertyDescriptor> CustomConfigurationHelper::GetProperties(
const gd::PropertiesContainer &properties,
const gd::SerializerElement &configurationContent) {
auto objectProperties = std::map<gd::String, gd::PropertyDescriptor>();
for (auto &property : properties.GetInternalVector()) {
const auto &propertyName = property->GetName();
const auto &propertyType = property->GetType();
// Copy the property
objectProperties[propertyName] = *property;
auto &newProperty = objectProperties[propertyName];
if (configurationContent.HasChild(propertyName)) {
if (propertyType == "String" || propertyType == "Choice" ||
propertyType == "Color" || propertyType == "Behavior" ||
propertyType == "Resource" || propertyType == "LeaderboardId" ||
propertyType == "AnimationName") {
newProperty.SetValue(
configurationContent.GetChild(propertyName).GetStringValue());
} else if (propertyType == "Number") {
newProperty.SetValue(gd::String::From(
configurationContent.GetChild(propertyName).GetDoubleValue()));
} else if (propertyType == "Boolean") {
newProperty.SetValue(
configurationContent.GetChild(propertyName).GetBoolValue()
? "true"
: "false");
}
} else {
// No value was serialized for this property. `newProperty`
// will have the default value coming from `enumeratedProperty`.
}
}
return objectProperties;
}
| @@ -53,7 +53,8 @@ std::map<gd::String, gd::PropertyDescriptor> CustomConfigurationHelper::GetPrope
if (configurationContent.HasChild(propertyName)) {
if (propertyType == "String" || propertyType == "Choice" ||
propertyType == "Color" || propertyType == "Behavior" ||
- propertyType == "Resource" || propertyType == "LeaderboardId") {
+ propertyType == "Resource" || propertyType == "LeaderboardId" ||
+ propertyType == "AnimationName") {
newProperty.SetValue(
configurationContent.GetChild(propertyName).GetStringValue());
} else if (propertyType == "Number") {
@@ -89,7 +90,8 @@ bool CustomConfigurationHelper::UpdateProperty(
if (propertyType == "String" || propertyType == "Choice" ||
propertyType == "Color" || propertyType == "Behavior" ||
- propertyType == "Resource" || propertyType == "LeaderboardId") {
+ propertyType == "Resource" || propertyType == "LeaderboardId" ||
+ propertyType == "AnimationName") {
element.SetStringValue(newValue);
} else if (propertyType == "Number") {
element.SetDoubleValue(newValue.To<double>()); | Core/GDCore/Project/CustomConfigurationHelper.cpp | 0 | C++ | 1 | none | 16 | 51 | 51 | true | AnimationName selector | 7,288 | 4ian/GDevelop | 10,154 | JavaScript | NeylMahfouf2608 | |
(props, ref) => {
const inputRef = React.useRef<?HTMLInputElement>(null);
React.useEffect(
() => {
// If the value passed changed, update the input. Otherwise,
// keep the input uncontrolled.
if (inputRef.current) inputRef.current.value = props.value;
},
[props.value]
);
const focus = React.useCallback((options: ?FocusOptions) => {
const input = inputRef.current;
if (input) {
input.focus();
if (options && options.selectAll) {
input.select();
}
if (options && Number.isInteger(options.caretPosition)) {
const position = Number(options.caretPosition);
input.setSelectionRange(position, position);
}
}
}, []);
const forceSetSelection = React.useCallback(
(selectionStart: number, selectionEnd: number) => {
if (inputRef.current) {
inputRef.current.selectionStart = selectionStart;
inputRef.current.selectionEnd = selectionEnd;
}
},
[]
);
const getCaretPosition = React.useCallback(() => {
// Returns null for inputs of type number (See https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/selectionStart)
if (inputRef.current) return inputRef.current.selectionStart;
return 0;
}, []);
React.useImperativeHandle(ref, () => ({
focus,
forceSetSelection,
getCaretPosition,
}));
return ( | No issues found. | (props, ref) => {
const inputRef = React.useRef<?HTMLInputElement>(null);
React.useEffect(
() => {
// If the value passed changed, update the input. Otherwise,
// keep the input uncontrolled.
if (inputRef.current) inputRef.current.value = props.value;
},
[props.value]
);
const focus = React.useCallback((options: ?FocusOptions) => {
const input = inputRef.current;
if (input) {
input.focus();
if (options && options.selectAll) {
input.select();
}
if (options && Number.isInteger(options.caretPosition)) {
const position = Number(options.caretPosition);
input.setSelectionRange(position, position);
}
}
}, []);
const forceSetSelection = React.useCallback(
(selectionStart: number, selectionEnd: number) => {
if (inputRef.current) {
inputRef.current.selectionStart = selectionStart;
inputRef.current.selectionEnd = selectionEnd;
}
},
[]
);
const getCaretPosition = React.useCallback(() => {
// Returns null for inputs of type number (See https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/selectionStart)
if (inputRef.current) return inputRef.current.selectionStart;
return 0;
}, []);
React.useImperativeHandle(ref, () => ({
focus,
forceSetSelection,
getCaretPosition,
}));
return ( | @@ -7,7 +7,7 @@ import classNames from 'classnames';
type SimpleTextFieldProps = {|
disabled: boolean,
type: 'number' | 'text',
- onChange: (newValue: string, context: any) => void,
+ onChange: (newValue: string, context: any, reason: 'change' | 'blur') => void,
value: string,
hint?: string,
id: string,
@@ -88,6 +88,7 @@ export const SimpleTextField = React.memo<
);
const getCaretPosition = React.useCallback(() => {
+ // Returns null for inputs of type number (See https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/selectionStart)
if (inputRef.current) return inputRef.current.selectionStart;
return 0;
}, []);
@@ -115,21 +116,30 @@ export const SimpleTextField = React.memo<
onClick={stopPropagation}
onDoubleClick={stopPropagation}
onBlur={e => {
- props.onChange(e.currentTarget.value, props.additionalContext);
+ props.onChange(
+ e.currentTarget.value,
+ props.additionalContext,
+ 'blur'
+ );
}}
onChange={
props.directlyStoreValueChangesWhileEditing
? e => {
props.onChange(
e.currentTarget.value,
- props.additionalContext
+ props.additionalContext,
+ 'change'
);
}
: undefined
}
onKeyUp={e => {
if (shouldValidate(e)) {
- props.onChange(e.currentTarget.value, props.additionalContext);
+ props.onChange(
+ e.currentTarget.value,
+ props.additionalContext,
+ 'blur'
+ );
}
}}
style={props.italic ? styles.italic : undefined} | newIDE/app/src/UI/SimpleTextField.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Fix variable list usability | 7,290 | 4ian/GDevelop | 10,154 | JavaScript | AlexandreSi | |
task => task.chapterId === chapterId
);
if (!currentChapterProgress) {
newUserCourseProgress.progress.push({ chapterId, completedTasks: [] });
currentChapterProgress =
newUserCourseProgress.progress[
newUserCourseProgress.progress.length - 1
];
}
const indexInList = currentChapterProgress.completedTasks.indexOf(
taskIndex
);
if (completed) {
if (indexInList === -1) {
currentChapterProgress.completedTasks.push(taskIndex);
}
} else {
if (indexInList !== -1) {
currentChapterProgress.completedTasks.splice(indexInList, 1);
}
}
setUserCourseProgress(newUserCourseProgress);
},
[
userCourseProgress,
userId,
selectedCourse,
setUserCourseProgress,
onOpenLoginDialog,
]
);
const isTaskCompleted = React.useCallback(
(chapterId: string, taskIndex: number) => {
if (!userCourseProgress) return false;
const currentChapterProgress = userCourseProgress.progress.find(
task => task.chapterId === chapterId
);
if (!currentChapterProgress) return false;
return currentChapterProgress.completedTasks.indexOf(taskIndex) >= 0;
},
[userCourseProgress]
);
const getChapterCompletion = React.useCallback(
(chapterId: string): CourseChapterCompletion | null => {
if (!courseChapters) return null;
| No issues found. | task => task.chapterId === chapterId
);
if (!currentChapterProgress) {
newUserCourseProgress.progress.push({ chapterId, completedTasks: [] });
currentChapterProgress =
newUserCourseProgress.progress[
newUserCourseProgress.progress.length - 1
];
}
const indexInList = currentChapterProgress.completedTasks.indexOf(
taskIndex
);
if (completed) {
if (indexInList === -1) {
currentChapterProgress.completedTasks.push(taskIndex);
}
} else {
if (indexInList !== -1) {
currentChapterProgress.completedTasks.splice(indexInList, 1);
}
}
setUserCourseProgress(newUserCourseProgress);
},
[
userCourseProgress,
userId,
selectedCourse,
setUserCourseProgress,
onOpenLoginDialog,
]
);
const isTaskCompleted = React.useCallback(
(chapterId: string, taskIndex: number) => {
if (!userCourseProgress) return false;
const currentChapterProgress = userCourseProgress.progress.find(
task => task.chapterId === chapterId
);
if (!currentChapterProgress) return false;
return currentChapterProgress.completedTasks.indexOf(taskIndex) >= 0;
},
[userCourseProgress]
);
const getChapterCompletion = React.useCallback(
(chapterId: string): CourseChapterCompletion | null => {
if (!courseChapters) return null;
| @@ -67,9 +67,10 @@ const useCourses = () => {
updateUserCourseProgress
);
- const [isLoadingChapters, setIsLoadingChapters] = React.useState<boolean>(
+ const [areChaptersReady, setAreChaptersReady] = React.useState<boolean>(
false
);
+
const [
courseChapters,
setCourseChapters,
@@ -85,7 +86,6 @@ const useCourses = () => {
const fetchCourseChapters = React.useCallback(
async (courseId: string) => {
- setIsLoadingChapters(true);
try {
const [fetchedChapters, userProgress] = await Promise.all([
listCourseChapters(getAuthorizationHeader, {
@@ -108,8 +108,9 @@ const useCourses = () => {
]);
setUserCourseProgressImmediately(userProgress);
setCourseChapters(fetchedChapters);
- } finally {
- setIsLoadingChapters(false);
+ setAreChaptersReady(true);
+ } catch (error) {
+ console.error('An error occurred while fetching courses:', error);
}
},
// A subscription change will change the displayed chapters sent by the backend.
@@ -347,7 +348,7 @@ const useCourses = () => {
courses,
courseChapters,
selectedCourse,
- isLoadingChapters,
+ areChaptersReady,
onCompleteTask,
isTaskCompleted,
getChapterCompletion, | newIDE/app/src/MainFrame/EditorContainers/HomePage/UseCourses.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Wait for courses to load before opening them | 7,304 | 4ian/GDevelop | 10,154 | JavaScript | AlexandreSi | |
object,
} = await setupObjectAndGetDomElementContainer();
// Check the default size.
expect(object.getWidth()).to.be(300);
expect(object.getHeight()).to.be(30);
expect(gameDomElementContainer.hasChildNodes()).to.be(true);
const inputElement = gameDomElementContainer.querySelector('input');
if (!inputElement)
throw new Error(
'Expected an input element to have been created by the object.'
);
expect(inputElement.value).to.be('My value');
// Clean up - not mandatory but to avoid overloading the testing browser.
runtimeScene.unloadScene();
});
it('destroys the DOM element when the scene is paused/resumed/stopped', async () => {
const {
runtimeScene,
gameDomElementContainer,
} = await setupObjectAndGetDomElementContainer();
expect(gameDomElementContainer.querySelector('input')).not.to.be(null);
// Check that it is updated according to the lifecycle of the scene
runtimeScene.onPause();
expect(gameDomElementContainer.querySelector('input')).to.be(null);
runtimeScene.onResume();
expect(gameDomElementContainer.querySelector('input')).not.to.be(null);
runtimeScene.unloadScene();
expect(gameDomElementContainer.querySelector('input')).to.be(null);
// Clean up - not mandatory but to avoid overloading the testing browser.
runtimeScene.unloadScene();
});
it('changes the DOM element when the object type is updated', async () => {
const {
runtimeScene,
gameDomElementContainer,
object,
} = await setupObjectAndGetDomElementContainer();
expect(gameDomElementContainer.querySelector('input')).not.to.be(null); | No issues found. | object,
} = await setupObjectAndGetDomElementContainer();
// Check the default size.
expect(object.getWidth()).to.be(300);
expect(object.getHeight()).to.be(30);
expect(gameDomElementContainer.hasChildNodes()).to.be(true);
const inputElement = gameDomElementContainer.querySelector('input');
if (!inputElement)
throw new Error(
'Expected an input element to have been created by the object.'
);
expect(inputElement.value).to.be('My value');
// Clean up - not mandatory but to avoid overloading the testing browser.
runtimeScene.unloadScene();
});
it('destroys the DOM element when the scene is paused/resumed/stopped', async () => {
const {
runtimeScene,
gameDomElementContainer,
} = await setupObjectAndGetDomElementContainer();
expect(gameDomElementContainer.querySelector('input')).not.to.be(null);
// Check that it is updated according to the lifecycle of the scene
runtimeScene.onPause();
expect(gameDomElementContainer.querySelector('input')).to.be(null);
runtimeScene.onResume();
expect(gameDomElementContainer.querySelector('input')).not.to.be(null);
runtimeScene.unloadScene();
expect(gameDomElementContainer.querySelector('input')).to.be(null);
// Clean up - not mandatory but to avoid overloading the testing browser.
runtimeScene.unloadScene();
});
it('changes the DOM element when the object type is updated', async () => {
const {
runtimeScene,
gameDomElementContainer,
object,
} = await setupObjectAndGetDomElementContainer();
expect(gameDomElementContainer.querySelector('input')).not.to.be(null); | @@ -25,6 +25,9 @@ describe('gdjs.TextInputRuntimeObject (using a PixiJS RuntimeGame with DOM eleme
borderWidth: 2,
disabled: false,
readOnly: false,
+ padding: 0,
+ textAlign: 'left',
+ maxLength: 20,
},
});
@@ -166,33 +169,33 @@ describe('gdjs.TextInputRuntimeObject (using a PixiJS RuntimeGame with DOM eleme
object,
} = await setupObjectAndGetDomElementContainer();
- const inputElement = gameDomElementContainer.querySelector('input');
- if (!inputElement) throw new Error('Expected input element to be found');
+ const formElement = gameDomElementContainer.querySelector('form');
+ if (!formElement) throw new Error('Expected form element to be found');
// Check visibility of the DOM element is visible by default, if it should be visible
// on the screen.
runtimeScene.renderAndStep(1000 / 60);
- expect(inputElement.style.display).to.be('initial');
+ expect(formElement.style.display).to.be('initial');
// Check visibility of the DOM element is updated at each frame,
// according to the object visibility.
object.hide(true);
runtimeScene.renderAndStep(1000 / 60);
- expect(inputElement.style.display).to.be('none');
+ expect(formElement.style.display).to.be('none');
object.hide(false);
runtimeScene.renderAndStep(1000 / 60);
- expect(inputElement.style.display).to.be('initial');
+ expect(formElement.style.display).to.be('initial');
// Check visibility of the DOM element is updated at each frame,
// according to the layer visibility.
runtimeScene.getLayer('').show(false);
runtimeScene.renderAndStep(1000 / 60);
- expect(inputElement.style.display).to.be('none');
+ expect(formElement.style.display).to.be('none');
runtimeScene.getLayer('').show(true);
runtimeScene.renderAndStep(1000 / 60);
- expect(inputElement.style.display).to.be('initial');
+ expect(formElement.style.display).t | Extensions/TextInput/tests/textinputruntimeobject.pixiruntimegamewithassets.spec.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Improvement features for Input text box | 7,308 | 4ian/GDevelop | 10,154 | JavaScript | NeylMahfouf2608 | |
if (field.current) field.current.focus(options);
};
React.useImperativeHandle(ref, () => ({
focus,
}));
// If the current value is not in the list, display an expression field.
const [isExpressionField, setIsExpressionField] = React.useState(
!!props.value && !isValidLiteralMouseButton(props.value)
);
const switchFieldType = () => {
setIsExpressionField(!isExpressionField);
};
const onChangeSelectValue = (event, value) => {
props.onChange(event.target.value);
};
const onChangeTextValue = (value: string) => {
props.onChange(value);
};
const fieldLabel = props.parameterMetadata
? props.parameterMetadata.getDescription()
: undefined;
const selectOptions = mouseButtons.map(({ value, label }) => {
return <SelectOption key={value} value={`"${value}"`} label={label} />;
});
return (
<TextFieldWithButtonLayout
renderTextField={() =>
!isExpressionField ? (
<SelectField
ref={field}
id={
props.parameterIndex !== undefined
? `parameter-${props.parameterIndex}-mouse-button-field`
: undefined
}
value={props.value}
onChange={onChangeSelectValue}
margin={props.isInline ? 'none' : 'dense'}
fullWidth
floatingLabelText={fieldLabel}
translatableHintText={t`Choose a mouse button`}
helperMarkdownText={
(props.parameterMetadata &&
props.parameterMetadata.getLongDescription()) || | No issues found. | if (field.current) field.current.focus(options);
};
React.useImperativeHandle(ref, () => ({
focus,
}));
// If the current value is not in the list, display an expression field.
const [isExpressionField, setIsExpressionField] = React.useState(
!!props.value && !isValidLiteralMouseButton(props.value)
);
const switchFieldType = () => {
setIsExpressionField(!isExpressionField);
};
const onChangeSelectValue = (event, value) => {
props.onChange(event.target.value);
};
const onChangeTextValue = (value: string) => {
props.onChange(value);
};
const fieldLabel = props.parameterMetadata
? props.parameterMetadata.getDescription()
: undefined;
const selectOptions = mouseButtons.map(({ value, label }) => {
return <SelectOption key={value} value={`"${value}"`} label={label} />;
});
return (
<TextFieldWithButtonLayout
renderTextField={() =>
!isExpressionField ? (
<SelectField
ref={field}
id={
props.parameterIndex !== undefined
? `parameter-${props.parameterIndex}-mouse-button-field`
: undefined
}
value={props.value}
onChange={onChangeSelectValue}
margin={props.isInline ? 'none' : 'dense'}
fullWidth
floatingLabelText={fieldLabel}
translatableHintText={t`Choose a mouse button`}
helperMarkdownText={
(props.parameterMetadata &&
props.parameterMetadata.getLongDescription()) || | @@ -33,6 +33,28 @@ const mouseButtons = [
label: t`Forward (Additional button, typically the Browser Forward button)`,
},
];
+const mouseButtonsSet = new Set(mouseButtons.map(button => button.value));
+
+const stringRegex = /^"(\w*)"$/;
+
+const isValidLiteralMouseButton = (expression: string): boolean => {
+ const matches = expression.match(stringRegex);
+ return matches && matches[1] !== undefined
+ ? mouseButtonsSet.has(matches[1])
+ : // the expression is not a literal value
+ false;
+};
+
+// This is not the negation of the function above as both return false for
+// non-literal expressions.
+const isInvalidLiteralMouseButton = (expression: string): boolean => {
+ const matches = expression.match(stringRegex);
+ // Return true by default as it could be an expression.
+ return matches && matches[1] !== undefined
+ ? !mouseButtonsSet.has(matches[1])
+ : // the expression is not a literal value
+ false;
+};
export default React.forwardRef<ParameterFieldProps, ParameterFieldInterface>(
function MouseButtonField(props, ref) {
@@ -48,13 +70,9 @@ export default React.forwardRef<ParameterFieldProps, ParameterFieldInterface>(
focus,
}));
- const isCurrentValueInList = mouseButtons.some(
- mouseButton => `"${mouseButton.value}"` === props.value
- );
-
// If the current value is not in the list, display an expression field.
const [isExpressionField, setIsExpressionField] = React.useState(
- !!props.value && !isCurrentValueInList
+ !!props.value && !isValidLiteralMouseButton(props.value)
);
const switchFieldType = () => {
@@ -144,13 +162,20 @@ export default React.forwardRef<ParameterFieldProps, ParameterFieldInterface>(
export const renderInlineMouseButton = ({
value,
+ expressionIsValid,
InvalidParameterValue,
}: ParameterInlineRendererProps) => {
- return value ? (
+ if (!value) {
+ return (
+ <InvalidParameterValue isEmpty>
+ <Trans>Choose a mo | newIDE/app/src/EventsSheet/ParameterFields/MouseButtonField.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Fix syntax errors not showing up on mouse button and key parameters | 7,320 | 4ian/GDevelop | 10,154 | JavaScript | D8H | |
import React from 'react';
import SvgIcon from '@material-ui/core/SvgIcon';
export default React.memo(props => (
<SvgIcon {...props} width="16" height="16" viewBox="0 0 16 16" fill="none">
<rect
x="0.5"
y="0.5"
width="15"
height="15"
rx="3.5"
stroke="currentColor"
fill="none"
/>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M5.49303 6.80026C5.69538 6.61236 6.01175 6.62408 6.19965 6.82643L7.99992 8.76519L9.80019 6.82643C9.98809 6.62408 10.3045 6.61236 10.5068 6.80026C10.7092 6.98816 10.7209 7.30453 10.533 7.50688L8.36632 9.84022C8.27171 9.9421 8.13896 9.99999 7.99992 9.99999C7.86089 9.99999 7.72813 9.9421 7.63352 9.84022L5.46686 7.50688C5.27896 7.30453 5.29067 6.98816 5.49303 6.80026Z"
fill="currentColor"
/>
</SvgIcon>
));
| No issues found. | import React from 'react';
import SvgIcon from '@material-ui/core/SvgIcon';
export default React.memo(props => (
<SvgIcon {...props} width="16" height="16" viewBox="0 0 16 16" fill="none">
<rect
x="0.5"
y="0.5"
width="15"
height="15"
rx="3.5"
stroke="currentColor"
fill="none"
/>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M5.49303 6.80026C5.69538 6.61236 6.01175 6.62408 6.19965 6.82643L7.99992 8.76519L9.80019 6.82643C9.98809 6.62408 10.3045 6.61236 10.5068 6.80026C10.7092 6.98816 10.7209 7.30453 10.533 7.50688L8.36632 9.84022C8.27171 9.9421 8.13896 9.99999 7.99992 9.99999C7.86089 9.99999 7.72813 9.9421 7.63352 9.84022L5.46686 7.50688C5.27896 7.30453 5.29067 6.98816 5.49303 6.80026Z"
fill="currentColor"
/>
</SvgIcon>
));
| @@ -0,0 +1,22 @@
+import React from 'react';
+import SvgIcon from '@material-ui/core/SvgIcon';
+
+export default React.memo(props => (
+ <SvgIcon {...props} width="16" height="16" viewBox="0 0 16 16" fill="none">
+ <rect
+ x="0.5"
+ y="0.5"
+ width="15"
+ height="15"
+ rx="3.5"
+ stroke="currentColor"
+ fill="none"
+ />
+ <path
+ fillRule="evenodd"
+ clipRule="evenodd"
+ d="M5.49303 6.80026C5.69538 6.61236 6.01175 6.62408 6.19965 6.82643L7.99992 8.76519L9.80019 6.82643C9.98809 6.62408 10.3045 6.61236 10.5068 6.80026C10.7092 6.98816 10.7209 7.30453 10.533 7.50688L8.36632 9.84022C8.27171 9.9421 8.13896 9.99999 7.99992 9.99999C7.86089 9.99999 7.72813 9.9421 7.63352 9.84022L5.46686 7.50688C5.27896 7.30453 5.29067 6.98816 5.49303 6.80026Z"
+ fill="currentColor"
+ />
+ </SvgIcon>
+)); | newIDE/app/src/UI/CustomSvgIcons/ChevronArrowDownWithRoundedBorder.js | 0 | JavaScript | 1 | none | 16 | 23 | 23 | true | Consistency on arrows | 7,322 | 4ian/GDevelop | 10,154 | JavaScript | Bouh | |
.getEvents()
.unserializeFrom(project, eventsSerializerElement);
gd.WholeProjectRefactorer.ensureBehaviorEventsFunctionsProperParameters(
eventsFunctionsExtension,
eventsBasedBehavior
);
const { runtimeScene, behavior } = generatedBehavior(
gd,
project,
eventsFunctionsExtension,
eventsBasedBehavior,
{ logCode: false }
);
// Check the default value is set.
expect(
runtimeScene
.getVariablesForExtension('MyExtension')
.get('MyVariable')
.getAsNumber()
).toBe(0);
behavior.MyFunction();
expect(
runtimeScene
.getVariablesForExtension('MyExtension')
.get('MyVariable')
.getAsNumber()
).toBe(456);
});
it('Can use a property in a variable condition (with name collisions)', () => {
const project = new gd.ProjectHelper.createNewGDJSProject();
const scene = project.insertNewLayout('MyScene', 0);
const eventsFunctionsExtension = project.insertNewEventsFunctionsExtension(
'MyExtension',
0
);
const eventsBasedBehavior = eventsFunctionsExtension
.getEventsBasedBehaviors()
.insertNew('MyBehavior', 0);
eventsBasedBehavior
.getPropertyDescriptors()
.insertNew('MyIdentifier', 0)
.setValue('123')
.setType('Number');
// Extension scene variable with the same name as the property.
eventsFunctionsExtension | No issues found. | .getEvents()
.unserializeFrom(project, eventsSerializerElement);
gd.WholeProjectRefactorer.ensureBehaviorEventsFunctionsProperParameters(
eventsFunctionsExtension,
eventsBasedBehavior
);
const { runtimeScene, behavior } = generatedBehavior(
gd,
project,
eventsFunctionsExtension,
eventsBasedBehavior,
{ logCode: false }
);
// Check the default value is set.
expect(
runtimeScene
.getVariablesForExtension('MyExtension')
.get('MyVariable')
.getAsNumber()
).toBe(0);
behavior.MyFunction();
expect(
runtimeScene
.getVariablesForExtension('MyExtension')
.get('MyVariable')
.getAsNumber()
).toBe(456);
});
it('Can use a property in a variable condition (with name collisions)', () => {
const project = new gd.ProjectHelper.createNewGDJSProject();
const scene = project.insertNewLayout('MyScene', 0);
const eventsFunctionsExtension = project.insertNewEventsFunctionsExtension(
'MyExtension',
0
);
const eventsBasedBehavior = eventsFunctionsExtension
.getEventsBasedBehaviors()
.insertNew('MyBehavior', 0);
eventsBasedBehavior
.getPropertyDescriptors()
.insertNew('MyIdentifier', 0)
.setValue('123')
.setType('Number');
// Extension scene variable with the same name as the property.
eventsFunctionsExtension | @@ -260,6 +260,71 @@ describe('libGD.js - GDJS Behavior Code Generation integration tests', function
expect(behavior._getMyProperty()).toBe(456);
});
+ it('Can use a property in a variable action when a parameter with the same name exits', () => {
+ const project = new gd.ProjectHelper.createNewGDJSProject();
+ const eventsFunctionsExtension = project.insertNewEventsFunctionsExtension(
+ 'MyExtension',
+ 0
+ );
+ const eventsBasedBehavior = eventsFunctionsExtension
+ .getEventsBasedBehaviors()
+ .insertNew('MyBehavior', 0);
+
+ eventsBasedBehavior
+ .getPropertyDescriptors()
+ .insertNew('MyIdentifier', 0)
+ .setValue('123')
+ .setType('Number');
+
+ const eventsSerializerElement = gd.Serializer.fromJSObject([
+ {
+ type: 'BuiltinCommonInstructions::Standard',
+ conditions: [],
+ actions: [
+ {
+ type: { value: 'SetNumberVariable' },
+ parameters: ['MyIdentifier', '=', '456'],
+ },
+ ],
+ },
+ ]);
+ eventsBasedBehavior
+ .getEventsFunctions()
+ .insertNewEventsFunction('MyFunction', 0)
+ .getEvents()
+ .unserializeFrom(project, eventsSerializerElement);
+ gd.WholeProjectRefactorer.ensureBehaviorEventsFunctionsProperParameters(
+ eventsFunctionsExtension,
+ eventsBasedBehavior
+ );
+ // Add a parameter with the same name as the property.
+ // It won't be used as SetNumberVariable has a variableOrProperty parameter.
+ const eventsFunction = eventsBasedBehavior
+ .getEventsFunctions()
+ .insertNewEventsFunction('MyFunction', 0);
+ const parameter = eventsFunction
+ .getParameters()
+ .insertNewParameter(
+ 'MyIdentifier',
+ eventsFunction.getParameters().getParametersCount()
+ );
+ parameter.setType('number');
+
+ const { runtimeScene, behavior } = generatedBehavior(
+ gd,
+ project,
+ eventsFunctionsExtension,
+ | GDevelop.js/__tests__/GDJSBehaviorCodeGenerationIntegrationTests.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Fix conflict between variable or property and parameter in variable setters | 7,329 | 4ian/GDevelop | 10,154 | JavaScript | D8H | |
const matchB = resultB.matches.find(match => match.key === key);
if (matchA && matchB) {
if (
matchA.closestExactMatchAtStartOfWordIndex !== null &&
matchB.closestExactMatchAtStartOfWordIndex !== null
) {
return (
matchA.closestExactMatchAtStartOfWordIndex -
matchB.closestExactMatchAtStartOfWordIndex
);
}
if (
matchA.closestExactMatchAtStartOfWordIndex !== null &&
matchB.closestExactMatchAtStartOfWordIndex === null
) {
return -1;
}
if (
matchA.closestExactMatchAtStartOfWordIndex === null &&
matchB.closestExactMatchAtStartOfWordIndex !== null
) {
return 1;
}
if (
matchA.closestExactMatchIndex !== null &&
matchB.closestExactMatchIndex !== null
) {
return matchA.closestExactMatchIndex - matchB.closestExactMatchIndex;
}
if (
matchA.closestExactMatchIndex !== null &&
matchB.closestExactMatchIndex === null
) {
return -1;
}
if (
matchA.closestExactMatchIndex === null &&
matchB.closestExactMatchIndex !== null
) {
return 1;
}
}
}
// At that point, neither result have an exact match anywhere.
if (resultA.score !== undefined && resultB.score !== undefined) {
return resultA.score - resultB.score;
}
return -(resultA.matches.length - resultB.matches.length);
};
};
| No issues found. | const matchB = resultB.matches.find(match => match.key === key);
if (matchA && matchB) {
if (
matchA.closestExactMatchAtStartOfWordIndex !== null &&
matchB.closestExactMatchAtStartOfWordIndex !== null
) {
return (
matchA.closestExactMatchAtStartOfWordIndex -
matchB.closestExactMatchAtStartOfWordIndex
);
}
if (
matchA.closestExactMatchAtStartOfWordIndex !== null &&
matchB.closestExactMatchAtStartOfWordIndex === null
) {
return -1;
}
if (
matchA.closestExactMatchAtStartOfWordIndex === null &&
matchB.closestExactMatchAtStartOfWordIndex !== null
) {
return 1;
}
if (
matchA.closestExactMatchIndex !== null &&
matchB.closestExactMatchIndex !== null
) {
return matchA.closestExactMatchIndex - matchB.closestExactMatchIndex;
}
if (
matchA.closestExactMatchIndex !== null &&
matchB.closestExactMatchIndex === null
) {
return -1;
}
if (
matchA.closestExactMatchIndex === null &&
matchB.closestExactMatchIndex !== null
) {
return 1;
}
}
}
// At that point, neither result have an exact match anywhere.
if (resultA.score !== undefined && resultB.score !== undefined) {
return resultA.score - resultB.score;
}
return -(resultA.matches.length - resultB.matches.length);
};
};
| @@ -23,9 +23,19 @@ export type SearchMatch = {|
indices: number[][],
value: string,
|};
+export type AugmentedSearchMatch = {|
+ ...SearchMatch,
+ closestExactMatchAtStartOfWordIndex: number | null,
+ closestExactMatchIndex: number | null,
+|};
export type SearchResult<T> = {|
item: T,
matches: SearchMatch[],
+ score?: number,
+|};
+export type AugmentedSearchResult<T> = {|
+ ...SearchResult<T>,
+ matches: AugmentedSearchMatch[],
|};
type SearchOptions = {|
@@ -83,6 +93,11 @@ export const getFuseSearchQueryForMultipleKeys = (
};
};
+/**
+ * Method that optimizes the match object returned by Fuse.js in the case
+ * the indices are used to display the matches.
+ * It gets rid of the indices that do not match the search text exactly.
+ */
const tuneMatchIndices = (match: SearchMatch, searchText: string) => {
const lowerCaseSearchText = searchText.toLowerCase();
return match.indices
@@ -111,13 +126,171 @@ const tuneMatchIndices = (match: SearchMatch, searchText: string) => {
.filter(Boolean);
};
+const getFirstExactMatchPosition = (
+ match: SearchMatch,
+ lowerCaseSearchText: string
+) => {
+ let closestExactMatchIndex = null;
+ let closestExactMatchAtStartOfWordIndex = null;
+ for (const index of match.indices) {
+ const lowerCaseMatchedText = match.value
+ .slice(index[0], index[1] + 1)
+ .toLowerCase();
+ // Using startsWith here instead of `===` because of this behavior of Fuse.js:
+ // Searching `trig` will return the instruction `Trigger once` but the match first index
+ // will be on the `Trigg` part of `Trigger once`, and not only on the part `Trig`,
+ // because the `g` is repeated.
+ const doesMatch = lowerCaseMatchedText.startsWith(lowerCaseSearchText);
+ if (!doesMatch) continue;
+ if (closestExactMatchIndex === null) {
+ closestExactMatchIndex = index[0];
+ }
+ if (closestExactMatchAtStartOfWordIndex === null) {
+ const characterBeforeMatch =
+ index[ | newIDE/app/src/UI/Search/UseSearchStructuredItem.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Return exact matches when searching for an instruction | 7,330 | 4ian/GDevelop | 10,154 | JavaScript | AlexandreSi | |
.addExpressionAndConditionAndAction(
'string',
'InputType',
_('Input type'),
_('the input type'),
_('the input type'),
_('Type'),
'res/conditions/text24_black.png'
)
.addParameter('object', _('Text input'), 'TextInputObject', false)
.useStandardParameters(
'stringWithSelector',
gd.ParameterOptions.makeNewOptions()
.setDescription(_('Input type'))
.setTypeExtraInfo(
JSON.stringify([
'text',
'text area',
'email',
'password',
'number',
'telephone number',
'url',
'search',
])
)
)
.setFunctionName('setInputType')
.setGetter('getInputType');
object
.addScopedAction(
'SetTextColor',
_('Text color'),
_('Set the text color of the object.'),
_('Set the text color of _PARAM0_ to _PARAM1_'),
_('Field appearance'),
'res/actions/color24.png',
'res/actions/color.png'
)
.addParameter('object', _('Text input'), 'TextInputObject', false)
.addParameter('color', _('Color'), '', false)
.getCodeExtraInformation()
.setFunctionName('setTextColor');
object
.addScopedAction(
'SetFillColor',
_('Fill color'),
_('Set the fill color of the object.'),
_('Set the fill color of _PARAM0_ to _PARAM1_'), | No issues found. | .addExpressionAndConditionAndAction(
'string',
'InputType',
_('Input type'),
_('the input type'),
_('the input type'),
_('Type'),
'res/conditions/text24_black.png'
)
.addParameter('object', _('Text input'), 'TextInputObject', false)
.useStandardParameters(
'stringWithSelector',
gd.ParameterOptions.makeNewOptions()
.setDescription(_('Input type'))
.setTypeExtraInfo(
JSON.stringify([
'text',
'text area',
'email',
'password',
'number',
'telephone number',
'url',
'search',
])
)
)
.setFunctionName('setInputType')
.setGetter('getInputType');
object
.addScopedAction(
'SetTextColor',
_('Text color'),
_('Set the text color of the object.'),
_('Set the text color of _PARAM0_ to _PARAM1_'),
_('Field appearance'),
'res/actions/color24.png',
'res/actions/color.png'
)
.addParameter('object', _('Text input'), 'TextInputObject', false)
.addParameter('color', _('Color'), '', false)
.getCodeExtraInformation()
.setFunctionName('setTextColor');
object
.addScopedAction(
'SetFillColor',
_('Fill color'),
_('Set the fill color of the object.'),
_('Set the fill color of _PARAM0_ to _PARAM1_'), | @@ -81,8 +81,11 @@ module.exports = {
} else if (propertyName === 'maxLength') {
objectContent.maxLength = newValue;
return true;
- } else if (propertyName === 'padding') {
- objectContent.padding = newValue;
+ } else if (propertyName === 'paddingX') {
+ objectContent.paddingX = Math.max(0, parseFloat(newValue));
+ return true;
+ } else if (propertyName === 'paddingY') {
+ objectContent.paddingY = Math.max(0, parseFloat(newValue));
return true;
} else if (propertyName === 'textAlign') {
objectContent.textAlign = newValue;
@@ -210,11 +213,27 @@ module.exports = {
.setGroup(_('Border appearance'));
objectProperties
- .getOrCreate('padding')
- .setValue((objectContent.padding || 0).toString())
+ .getOrCreate('paddingX')
+ .setValue(
+ (objectContent.paddingX !== undefined
+ ? objectContent.paddingX
+ : 2
+ ).toString()
+ )
.setType('number')
- .setLabel(_('Padding'))
- .setGroup(_('Font'));
+ .setLabel(_('Padding (horizontal)'))
+ .setGroup(_('Field appearance'));
+ objectProperties
+ .getOrCreate('paddingY')
+ .setValue(
+ (objectContent.paddingY !== undefined
+ ? objectContent.paddingY
+ : 1
+ ).toString()
+ )
+ .setType('number')
+ .setLabel(_('Padding (vertical)'))
+ .setGroup(_('Field appearance'));
objectProperties
.getOrCreate('maxLength')
.setValue((objectContent.maxLength || 0).toString())
@@ -235,7 +254,7 @@ module.exports = {
.addExtraInfo('center')
.addExtraInfo('right')
.setLabel(_('Text alignment'))
- .setGroup(_('Font'));
+ .setGroup(_('Field appearance'));
return objectProperties;
};
@@ -253,7 +272,8 @@ module.exports = {
borderWidth: 1,
readOnly: false,
| Extensions/TextInput/JsExtension.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Split text input padding into 2 separate properties | 7,338 | 4ian/GDevelop | 10,154 | JavaScript | AlexandreSi | |
}
_getShowDeprecatedInstructionWarning() {
return this.state.values.showDeprecatedInstructionWarning;
}
_setUse3DEditor(use3DEditor: boolean) {
this.setState(
state => ({
values: {
...state.values,
use3DEditor,
},
}),
() => this._persistValuesToLocalStorage(this.state)
);
}
_getUse3DEditor() {
return this.state.values.use3DEditor;
}
_setShowBasicProfilingCounters(showBasicProfilingCounters: boolean) {
this.setState(
state => ({
values: {
...state.values,
showBasicProfilingCounters,
},
}),
() => this._persistValuesToLocalStorage(this.state)
);
}
_checkUpdates(forceDownload?: boolean) {
// Checking for updates is only done on Electron.
// Note: This could be abstracted away later if other updates mechanisms
// should be supported.
const { disableCheckForUpdates } = this.props;
if (!ipcRenderer || disableCheckForUpdates) return;
if (!!forceDownload || this.state.values.autoDownloadUpdates) {
ipcRenderer.send('updates-check-and-download');
} else {
ipcRenderer.send('updates-check');
}
}
_verifyIfIsNewVersion() {
const currentVersion = getIDEVersion();
const { lastLaunchedVersion } = this.state.values; | No issues found. | }
_getShowDeprecatedInstructionWarning() {
return this.state.values.showDeprecatedInstructionWarning;
}
_setUse3DEditor(use3DEditor: boolean) {
this.setState(
state => ({
values: {
...state.values,
use3DEditor,
},
}),
() => this._persistValuesToLocalStorage(this.state)
);
}
_getUse3DEditor() {
return this.state.values.use3DEditor;
}
_setShowBasicProfilingCounters(showBasicProfilingCounters: boolean) {
this.setState(
state => ({
values: {
...state.values,
showBasicProfilingCounters,
},
}),
() => this._persistValuesToLocalStorage(this.state)
);
}
_checkUpdates(forceDownload?: boolean) {
// Checking for updates is only done on Electron.
// Note: This could be abstracted away later if other updates mechanisms
// should be supported.
const { disableCheckForUpdates } = this.props;
if (!ipcRenderer || disableCheckForUpdates) return;
if (!!forceDownload || this.state.values.autoDownloadUpdates) {
ipcRenderer.send('updates-check-and-download');
} else {
ipcRenderer.send('updates-check');
}
}
_verifyIfIsNewVersion() {
const currentVersion = getIDEVersion();
const { lastLaunchedVersion } = this.state.values; | @@ -39,7 +39,6 @@ type Props = {|
type State = Preferences;
const localStorageItem = 'gd-preferences';
-const MAX_RECENT_FILES_COUNT = 20;
export const loadPreferencesFromLocalStorage = (): ?PreferencesValues => {
try {
@@ -85,7 +84,7 @@ export const getInitialPreferences = () => {
return { ...initialPreferences.values, language: languageOrLocale };
};
-const getPreferences = () => {
+const getPreferences = (): PreferencesValues => {
const preferences =
loadPreferencesFromLocalStorage() || getInitialPreferences();
setLanguageInDOM(preferences.language);
@@ -718,8 +717,12 @@ export default class PreferencesProvider extends React.Component<Props, State> {
);
}
- _getRecentProjectFiles() {
- return this.state.values.recentProjectFiles;
+ _getRecentProjectFiles(
+ options: ?{| limit: number |}
+ ): Array<FileMetadataAndStorageProviderName> {
+ const limit = options ? options.limit : undefined;
+ const recentProjectFiles = this.state.values.recentProjectFiles;
+ return limit ? recentProjectFiles.slice(0, limit) : recentProjectFiles;
}
_setRecentProjectFiles(recents: Array<FileMetadataAndStorageProviderName>) {
@@ -742,24 +745,19 @@ export default class PreferencesProvider extends React.Component<Props, State> {
const isNotNewRecentFile = recentFile =>
recentFile.fileMetadata.fileIdentifier !==
newRecentFile.fileMetadata.fileIdentifier;
- this._setRecentProjectFiles(
- [newRecentFile, ...recentProjectFiles.filter(isNotNewRecentFile)].slice(
- 0,
- MAX_RECENT_FILES_COUNT
- )
- );
+ this._setRecentProjectFiles([
+ newRecentFile,
+ ...recentProjectFiles.filter(isNotNewRecentFile),
+ ]);
}
_removeRecentProjectFile(recentFile: FileMetadataAndStorageProviderName) {
const isNotRemovedRecentFile = recentFileItem =>
recentFileItem.fileMetadata.fileIdentifier !==
recentFile.fileMetadata.fileIdentifier;
- this._setRecentProject | newIDE/app/src/MainFrame/Preferences/PreferencesProvider.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Fix a few issues with displaying projects correctly in the create section | 7,349 | 4ian/GDevelop | 10,154 | JavaScript | ClementPasteau | |
project,
instance,
associatedObjectConfiguration,
pixiContainer,
threeGroup,
PixiResourcesLoader
);
} else {
return new RenderedCustomObjectInstance(
project,
instance,
associatedObjectConfiguration,
pixiContainer,
threeGroup,
PixiResourcesLoader
);
}
}
console.warn(
`Object with type ${objectType} has no instance renderer registered. Please use registerInstanceRenderer to register your renderer.`
);
return new this.renderers['unknownObjectType'](
project,
instance,
associatedObjectConfiguration,
pixiContainer,
PixiResourcesLoader
);
}
},
registerInstanceRenderer: function(objectType: string, renderer: any) {
if (!renderer.getThumbnail) {
console.warn(
`Tried to register renderer for object "${objectType}", but getThumbnail is not defined.`
);
return;
}
if (this.renderers.hasOwnProperty(objectType)) {
console.warn(
`Tried to register renderer for object "${objectType}", but a renderer already exists.`
);
// If you want to update a renderer, this is currently unsupported.
// To implement this, we need to add support for instance renderers to be released/destroyed
// (some can have reference counting for some PIXI resources, etc... that would need to be properly released).
return;
}
this.renderers[objectType] = renderer; | No issues found. | project,
instance,
associatedObjectConfiguration,
pixiContainer,
threeGroup,
PixiResourcesLoader
);
} else {
return new RenderedCustomObjectInstance(
project,
instance,
associatedObjectConfiguration,
pixiContainer,
threeGroup,
PixiResourcesLoader
);
}
}
console.warn(
`Object with type ${objectType} has no instance renderer registered. Please use registerInstanceRenderer to register your renderer.`
);
return new this.renderers['unknownObjectType'](
project,
instance,
associatedObjectConfiguration,
pixiContainer,
PixiResourcesLoader
);
}
},
registerInstanceRenderer: function(objectType: string, renderer: any) {
if (!renderer.getThumbnail) {
console.warn(
`Tried to register renderer for object "${objectType}", but getThumbnail is not defined.`
);
return;
}
if (this.renderers.hasOwnProperty(objectType)) {
console.warn(
`Tried to register renderer for object "${objectType}", but a renderer already exists.`
);
// If you want to update a renderer, this is currently unsupported.
// To implement this, we need to add support for instance renderers to be released/destroyed
// (some can have reference counting for some PIXI resources, etc... that would need to be properly released).
return;
}
this.renderers[objectType] = renderer; | @@ -20,7 +20,11 @@ import * as PIXI_SPINE from 'pixi-spine';
import * as THREE from 'three';
import * as SkeletonUtils from 'three/examples/jsm/utils/SkeletonUtils';
import optionalRequire from '../Utils/OptionalRequire';
-import { rgbOrHexToHexNumber } from '../Utils/ColorTransformer';
+import {
+ rgbOrHexToHexNumber,
+ hexNumberToRGBArray,
+} from '../Utils/ColorTransformer';
+
const path = optionalRequire('path');
const electron = optionalRequire('electron');
const gd: libGDevelop = global.gd;
@@ -277,6 +281,7 @@ const ObjectsRenderingService = {
}
},
rgbOrHexToHexNumber, // Expose a ColorTransformer function, useful to manage different color types for the extensions
+ hexNumberToRGBArray, // Expose a ColorTransformer function, useful to manage different color types for the extensions
gd, // Expose gd so that it can be used by renderers
PIXI, // Expose PIXI so that it can be used by renderers
THREE, // Expose THREE so that it can be used by renderers | newIDE/app/src/ObjectsRendering/ObjectsRenderingService.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Tint color for 3D cube | 7,354 | 4ian/GDevelop | 10,154 | JavaScript | NeylMahfouf2608 | |
}
if (
!matchA &&
matchB &&
matchB.closestExactMatchAtStartOfWordIndex !== null
) {
return 1;
}
// If both result have exact matches in the key, give priority to the one where
// the match is closer to the start of the sentence.
if (matchA && matchB) {
if (
matchA.closestExactMatchAtStartOfWordIndex !== null &&
matchB.closestExactMatchAtStartOfWordIndex !== null
) {
return (
matchA.closestExactMatchAtStartOfWordIndex -
matchB.closestExactMatchAtStartOfWordIndex
);
}
if (
matchA.closestExactMatchAtStartOfWordIndex !== null &&
matchB.closestExactMatchAtStartOfWordIndex === null
) {
return -1;
}
if (
matchA.closestExactMatchAtStartOfWordIndex === null &&
matchB.closestExactMatchAtStartOfWordIndex !== null
) {
return 1;
}
if (
matchA.closestExactMatchIndex !== null &&
matchB.closestExactMatchIndex !== null
) {
return matchA.closestExactMatchIndex - matchB.closestExactMatchIndex;
}
if (
matchA.closestExactMatchIndex !== null &&
matchB.closestExactMatchIndex === null
) {
return -1;
}
if (
matchA.closestExactMatchIndex === null &&
matchB.closestExactMatchIndex !== null
) {
return 1;
}
} | No issues found. | }
if (
!matchA &&
matchB &&
matchB.closestExactMatchAtStartOfWordIndex !== null
) {
return 1;
}
// If both result have exact matches in the key, give priority to the one where
// the match is closer to the start of the sentence.
if (matchA && matchB) {
if (
matchA.closestExactMatchAtStartOfWordIndex !== null &&
matchB.closestExactMatchAtStartOfWordIndex !== null
) {
return (
matchA.closestExactMatchAtStartOfWordIndex -
matchB.closestExactMatchAtStartOfWordIndex
);
}
if (
matchA.closestExactMatchAtStartOfWordIndex !== null &&
matchB.closestExactMatchAtStartOfWordIndex === null
) {
return -1;
}
if (
matchA.closestExactMatchAtStartOfWordIndex === null &&
matchB.closestExactMatchAtStartOfWordIndex !== null
) {
return 1;
}
if (
matchA.closestExactMatchIndex !== null &&
matchB.closestExactMatchIndex !== null
) {
return matchA.closestExactMatchIndex - matchB.closestExactMatchIndex;
}
if (
matchA.closestExactMatchIndex !== null &&
matchB.closestExactMatchIndex === null
) {
return -1;
}
if (
matchA.closestExactMatchIndex === null &&
matchB.closestExactMatchIndex !== null
) {
return 1;
}
} | @@ -241,6 +241,24 @@ export const sortResultsUsingExactMatches = (orderedKeys: string[]) => {
for (const key of orderedKeys) {
const matchA = resultA.matches.find(match => match.key === key);
const matchB = resultB.matches.find(match => match.key === key);
+ // If a result has an exact math at the start of the word in the key but
+ // the other doesn't even has a match in the key, give priority.
+ if (
+ matchA &&
+ matchA.closestExactMatchAtStartOfWordIndex !== null &&
+ !matchB
+ ) {
+ return -1;
+ }
+ if (
+ !matchA &&
+ matchB &&
+ matchB.closestExactMatchAtStartOfWordIndex !== null
+ ) {
+ return 1;
+ }
+ // If both result have exact matches in the key, give priority to the one where
+ // the match is closer to the start of the sentence.
if (matchA && matchB) {
if (
matchA.closestExactMatchAtStartOfWordIndex !== null && | newIDE/app/src/UI/Search/UseSearchStructuredItem.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Refine free instructions search to give priority to exact matches at start of word | 7,360 | 4ian/GDevelop | 10,154 | JavaScript | AlexandreSi | |
project,
PixiResourcesLoader,
serializedObject
);
// The asset header is used because the Pixi texture will likely be invalid
// when the asset has just been downloaded.
const assetDimensions = assetShortHeader
? { width: assetShortHeader.width, height: assetShortHeader.height }
: getFirstFrameDimension(
project,
PixiResourcesLoader,
serializedAssetObject
);
if (!objectDimensions || !assetDimensions) {
return { scaleX: 1, scaleY: 1 };
}
const scaleX = assetDimensions.width / objectDimensions.width;
const scaleY = assetDimensions.height / objectDimensions.height;
return { scaleX, scaleY };
};
const evaluatePreScale = (
project: gdProject,
PixiResourcesLoader: any,
serializedObject: SpriteObjectDataType,
serializedAssetObject: SpriteObjectDataType,
assetShortHeader?: ?AssetShortHeader
) => {
const { scaleX, scaleY } = evaluateImageScale(
project,
PixiResourcesLoader,
serializedObject,
serializedAssetObject,
assetShortHeader
);
const objectPreScale = serializedObject.preScale || 1;
const assetPreScale = objectPreScale / Math.sqrt(scaleX * scaleY);
return assetPreScale > 0.5 &&
Math.abs(Math.round(assetPreScale) - assetPreScale) < 0.001
? Math.round(assetPreScale)
: assetPreScale;
};
const scalePoint = function<P: { x: number, y: number }>(
point: P,
scaleX: number,
scaleY: number
): P {
return {
...point,
x: point.x * scaleX, | No issues found. | project,
PixiResourcesLoader,
serializedObject
);
// The asset header is used because the Pixi texture will likely be invalid
// when the asset has just been downloaded.
const assetDimensions = assetShortHeader
? { width: assetShortHeader.width, height: assetShortHeader.height }
: getFirstFrameDimension(
project,
PixiResourcesLoader,
serializedAssetObject
);
if (!objectDimensions || !assetDimensions) {
return { scaleX: 1, scaleY: 1 };
}
const scaleX = assetDimensions.width / objectDimensions.width;
const scaleY = assetDimensions.height / objectDimensions.height;
return { scaleX, scaleY };
};
const evaluatePreScale = (
project: gdProject,
PixiResourcesLoader: any,
serializedObject: SpriteObjectDataType,
serializedAssetObject: SpriteObjectDataType,
assetShortHeader?: ?AssetShortHeader
) => {
const { scaleX, scaleY } = evaluateImageScale(
project,
PixiResourcesLoader,
serializedObject,
serializedAssetObject,
assetShortHeader
);
const objectPreScale = serializedObject.preScale || 1;
const assetPreScale = objectPreScale / Math.sqrt(scaleX * scaleY);
return assetPreScale > 0.5 &&
Math.abs(Math.round(assetPreScale) - assetPreScale) < 0.001
? Math.round(assetPreScale)
: assetPreScale;
};
const scalePoint = function<P: { x: number, y: number }>(
point: P,
scaleX: number,
scaleY: number
): P {
return {
...point,
x: point.x * scaleX, | @@ -81,10 +81,18 @@ type SpriteObjectDataType = {
animations: Array<SpriteAnimationData>,
};
-export const canSwapAssetOfObject = (object: gdObject) => {
- const type = object.getType();
- return type === 'Scene3D::Model3DObject' || type === 'Sprite';
-};
+const unswappableObjectTypes = [
+ 'BBText::BBText',
+ 'TextObject::Text',
+ 'Lighting::LightObject',
+ 'PrimitiveDrawing::Drawer',
+ 'TileMap::TileMap',
+ 'TileMap::CollisionMask',
+ 'TileMap::SimpleTileMap',
+ 'Video::VideoObject',
+];
+export const canSwapAssetOfObject = (object: gdObject) =>
+ !unswappableObjectTypes.includes(object.getType());
const mergeAnimations = function<A: { name: string }>(
project: gdProject,
@@ -312,7 +320,7 @@ export const swapAsset = (
assetObject: gdObject,
assetShortHeader?: ?AssetShortHeader
) => {
- const serializedObject = serializeToJSObject(object);
+ let serializedObject = serializeToJSObject(object);
const serializedAssetObject = serializeToJSObject(assetObject);
if (object.getType() === 'Sprite') {
@@ -338,6 +346,7 @@ export const swapAsset = (
scaleX,
scaleY
);
+ serializedObject.assetStoreId = serializedAssetObject.assetStoreId;
} else if (object.getType() === 'Scene3D::Model3DObject') {
const objectVolume =
serializedObject.content.width *
@@ -365,6 +374,15 @@ export const swapAsset = (
centerLocation: serializedObject.content.centerLocation,
};
serializedObject.assetStoreId = serializedAssetObject.assetStoreId;
+ } else {
+ serializedObject = {
+ ...serializedAssetObject,
+ name: serializedObject.name,
+ type: serializedObject.type,
+ variables: serializedObject.variables,
+ behaviors: serializedObject.behaviors,
+ effects: serializedObject.effects,
+ };
}
unserializeFromJSObject(object, serializedObject, 'unserializeFrom', project);
}; | newIDE/app/src/AssetStore/AssetSwapper.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Allow to swap assets of any object type | 7,365 | 4ian/GDevelop | 10,154 | JavaScript | D8H | |
setTextInput('');
};
React.useEffect(
() => {
if (open && shouldAutofocus && !confirmText) {
// If the dialog is opened and autofocus should be set and there is no confirm text
// to enter, focus Confirm button to enable quick deletion with only keyboard navigation.
setTimeout(
() => {
if (confirmButtonRef.current) {
confirmButtonRef.current.focus();
}
},
// Wait for component to be mounted so that confirmButtonRef targets something.
50
);
}
},
[open, shouldAutofocus, confirmText]
);
return (
<I18n>
{({ i18n }) => (
<Dialog
title={i18n._(props.title)}
open={open}
dangerLevel="danger"
onApply={onConfirm}
onRequestClose={props.onDismiss}
maxWidth="sm"
flexColumnBody
actions={[
<FlatButton
key="cancel"
label={
props.dismissButtonLabel ? (
i18n._(props.dismissButtonLabel)
) : (
<Trans>Cancel</Trans>
)
}
primary={false}
onClick={props.onDismiss}
/>,
<DialogPrimaryButton
key="confirm"
ref={confirmButtonRef}
color="danger"
label={ | No issues found. | setTextInput('');
};
React.useEffect(
() => {
if (open && shouldAutofocus && !confirmText) {
// If the dialog is opened and autofocus should be set and there is no confirm text
// to enter, focus Confirm button to enable quick deletion with only keyboard navigation.
setTimeout(
() => {
if (confirmButtonRef.current) {
confirmButtonRef.current.focus();
}
},
// Wait for component to be mounted so that confirmButtonRef targets something.
50
);
}
},
[open, shouldAutofocus, confirmText]
);
return (
<I18n>
{({ i18n }) => (
<Dialog
title={i18n._(props.title)}
open={open}
dangerLevel="danger"
onApply={onConfirm}
onRequestClose={props.onDismiss}
maxWidth="sm"
flexColumnBody
actions={[
<FlatButton
key="cancel"
label={
props.dismissButtonLabel ? (
i18n._(props.dismissButtonLabel)
) : (
<Trans>Cancel</Trans>
)
}
primary={false}
onClick={props.onDismiss}
/>,
<DialogPrimaryButton
key="confirm"
ref={confirmButtonRef}
color="danger"
label={ | @@ -11,6 +11,7 @@ import { LargeSpacer } from '../Grid';
import Text from '../Text';
import TextField from '../TextField';
import { useShouldAutofocusInput } from '../Responsive/ScreenTypeMeasurer';
+import { MarkdownText } from '../MarkdownText';
type Props = {|
open: boolean,
@@ -22,6 +23,7 @@ type Props = {|
onDismiss: () => void,
confirmButtonLabel?: MessageDescriptor,
dismissButtonLabel?: MessageDescriptor,
+ header?: React.Node,
|};
function ConfirmDeleteDialog(props: Props) {
@@ -98,8 +100,9 @@ function ConfirmDeleteDialog(props: Props) {
]}
fullscreen="never-even-on-mobile"
>
+ {props.header}
<Text size="body" style={{ userSelect: 'text' }}>
- {i18n._(props.message)}
+ <MarkdownText translatableSource={props.message} allowParagraphs />
</Text>
{props.confirmText && props.fieldMessage && (
<> | newIDE/app/src/UI/Alert/ConfirmDeleteDialog.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Add a clearer warning before the deletion of a game and a project. | 7,368 | 4ian/GDevelop | 10,154 | JavaScript | Bouh | |
value={gd.Variable.Boolean}
/>,
<SelectOption key="array" label={t`Array`} value={gd.Variable.Array} />,
<SelectOption
key="structure"
label={t`Structure`}
value={gd.Variable.Structure}
/>,
];
}
return options;
};
export const getVariableTypeToIcon = (): { [Variable_Type]: any } => {
if (!variableTypeToIcon) {
variableTypeToIcon = {
[gd.Variable.MixedTypes]: VariableMixedTypesIcon,
[gd.Variable.String]: VariableStringIcon,
[gd.Variable.Number]: VariableNumberIcon,
[gd.Variable.Boolean]: VariableBooleanIcon,
[gd.Variable.Array]: VariableArrayIcon,
[gd.Variable.Structure]: VariableStructureIcon,
};
}
return variableTypeToIcon;
};
const getVariableTypeToString = () => {
if (!variableTypeToString) {
variableTypeToString = {
[gd.Variable.String]: 'string',
[gd.Variable.Number]: 'number',
[gd.Variable.Boolean]: 'boolean',
[gd.Variable.Array]: 'array',
[gd.Variable.Structure]: 'structure',
};
}
return variableTypeToString;
};
const VariableTypeSelector = React.memo<Props>((props: Props) => {
const gdevelopTheme = React.useContext(GDevelopThemeContext);
const Icon = getVariableTypeToIcon()[props.variableType];
return (
<Line alignItems="center" noMargin>
{props.errorMessage ? (
<Tooltip title={props.errorMessage}>
<WarningIcon
fontSize="small"
htmlColor={gdevelopTheme.message.warning} | No issues found. | value={gd.Variable.Boolean}
/>,
<SelectOption key="array" label={t`Array`} value={gd.Variable.Array} />,
<SelectOption
key="structure"
label={t`Structure`}
value={gd.Variable.Structure}
/>,
];
}
return options;
};
export const getVariableTypeToIcon = (): { [Variable_Type]: any } => {
if (!variableTypeToIcon) {
variableTypeToIcon = {
[gd.Variable.MixedTypes]: VariableMixedTypesIcon,
[gd.Variable.String]: VariableStringIcon,
[gd.Variable.Number]: VariableNumberIcon,
[gd.Variable.Boolean]: VariableBooleanIcon,
[gd.Variable.Array]: VariableArrayIcon,
[gd.Variable.Structure]: VariableStructureIcon,
};
}
return variableTypeToIcon;
};
const getVariableTypeToString = () => {
if (!variableTypeToString) {
variableTypeToString = {
[gd.Variable.String]: 'string',
[gd.Variable.Number]: 'number',
[gd.Variable.Boolean]: 'boolean',
[gd.Variable.Array]: 'array',
[gd.Variable.Structure]: 'structure',
};
}
return variableTypeToString;
};
const VariableTypeSelector = React.memo<Props>((props: Props) => {
const gdevelopTheme = React.useContext(GDevelopThemeContext);
const Icon = getVariableTypeToIcon()[props.variableType];
return (
<Line alignItems="center" noMargin>
{props.errorMessage ? (
<Tooltip title={props.errorMessage}>
<WarningIcon
fontSize="small"
htmlColor={gdevelopTheme.message.warning} | @@ -2,6 +2,7 @@
import * as React from 'react';
import { t } from '@lingui/macro';
+import { type MessageDescriptor } from '../Utils/i18n/MessageDescriptor.flow';
import SelectField from '../UI/SelectField';
import SelectOption from '../UI/SelectOption';
import VariableStringIcon from './Icons/VariableStringIcon';
@@ -10,8 +11,10 @@ import VariableBooleanIcon from './Icons/VariableBooleanIcon';
import VariableArrayIcon from './Icons/VariableArrayIcon';
import VariableStructureIcon from './Icons/VariableStructureIcon';
import VariableMixedTypesIcon from '../UI/CustomSvgIcons/Cross';
+import WarningIcon from '../UI/CustomSvgIcons/Warning';
import { Line, Spacer } from '../UI/Grid';
import GDevelopThemeContext from '../UI/Theme/GDevelopThemeContext';
+import Tooltip from '@material-ui/core/Tooltip';
const gd = global.gd;
type Props = {|
@@ -21,6 +24,7 @@ type Props = {|
isHighlighted?: boolean,
readOnlyWithIcon?: boolean,
id?: string,
+ errorMessage: MessageDescriptor | null,
|};
let options;
@@ -85,14 +89,23 @@ const VariableTypeSelector = React.memo<Props>((props: Props) => {
return (
<Line alignItems="center" noMargin>
- <Icon
- fontSize="small"
- htmlColor={
- props.isHighlighted
- ? gdevelopTheme.listItem.selectedTextColor
- : undefined
- }
- />
+ {props.errorMessage ? (
+ <Tooltip title={props.errorMessage}>
+ <WarningIcon
+ fontSize="small"
+ htmlColor={gdevelopTheme.message.warning}
+ />
+ </Tooltip>
+ ) : (
+ <Icon
+ fontSize="small"
+ htmlColor={
+ props.isHighlighted
+ ? gdevelopTheme.message.selectedTextColor
+ : undefined
+ }
+ />
+ )}
{!props.readOnlyWithIcon && (
<>
<Spacer /> | newIDE/app/src/VariablesList/VariableTypeSelector.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Add a warning on array children with inconsistent type | 7,376 | 4ian/GDevelop | 10,154 | JavaScript | D8H | |
let nextStepIndex = stepIndex;
// Check if we can go directly to next mandatory (not-skippable) and not deprecated step.
while (nextStepIndex < stepCount - 1) {
if (
flow[nextStepIndex] &&
(flow[nextStepIndex].deprecated ||
(flow[nextStepIndex].skippable &&
isDomBasedTriggerComplete(
flow[nextStepIndex].nextStepTrigger,
data
)))
)
nextStepIndex += 1;
else break;
}
if (gatherData) {
const newData = gatherProjectDataOnMultipleSteps({
flow,
startIndex: currentStepIndex,
endIndex: nextStepIndex - 1,
data,
project,
});
setData(newData);
}
changeStep(nextStepIndex);
},
[flow, changeStep, stepCount, data, project, currentStepIndex]
);
// Compute phases start positions on flow change.
React.useEffect(
() => {
const indices = [];
for (
let flowStepIndex = 0;
flowStepIndex < tutorial.flow.length;
flowStepIndex++
) {
if (tutorial.flow[flowStepIndex].isCheckpoint) {
indices.push(flowStepIndex);
}
}
indices.push(tutorial.flow.length - 1); // Last phase ends at last flow step.
setEndIndicesPerPhase(indices);
},
[tutorial.flow]
);
| No issues found. | let nextStepIndex = stepIndex;
// Check if we can go directly to next mandatory (not-skippable) and not deprecated step.
while (nextStepIndex < stepCount - 1) {
if (
flow[nextStepIndex] &&
(flow[nextStepIndex].deprecated ||
(flow[nextStepIndex].skippable &&
isDomBasedTriggerComplete(
flow[nextStepIndex].nextStepTrigger,
data
)))
)
nextStepIndex += 1;
else break;
}
if (gatherData) {
const newData = gatherProjectDataOnMultipleSteps({
flow,
startIndex: currentStepIndex,
endIndex: nextStepIndex - 1,
data,
project,
});
setData(newData);
}
changeStep(nextStepIndex);
},
[flow, changeStep, stepCount, data, project, currentStepIndex]
);
// Compute phases start positions on flow change.
React.useEffect(
() => {
const indices = [];
for (
let flowStepIndex = 0;
flowStepIndex < tutorial.flow.length;
flowStepIndex++
) {
if (tutorial.flow[flowStepIndex].isCheckpoint) {
indices.push(flowStepIndex);
}
}
indices.push(tutorial.flow.length - 1); // Last phase ends at last flow step.
setEndIndicesPerPhase(indices);
},
[tutorial.flow]
);
| @@ -1,6 +1,5 @@
// @flow
import * as React from 'react';
-import { I18n } from '@lingui/react';
import { I18n as I18nType } from '@lingui/core';
import { useDebounce } from '../Utils/UseDebounce';
import { useInterval } from '../Utils/UseInterval';
@@ -428,6 +427,7 @@ type Props = {|
tutorial: InAppTutorial,
startStepIndex: number,
startProjectData: { [key: string]: string },
+ i18n: I18nType,
endTutorial: ({|
shouldCloseProject: boolean,
shouldWarnAboutUnsavedChanges: boolean,
@@ -445,6 +445,7 @@ export type InAppTutorialOrchestratorInterface = {|
projectData: {| [key: string]: string |},
|},
changeData: (oldName: string, newName: string) => void,
+ getPreviewMessage: () => {| message: string, position: string |} | null,
|};
const InAppTutorialOrchestrator = React.forwardRef<
@@ -460,6 +461,7 @@ const InAppTutorialOrchestrator = React.forwardRef<
currentSceneName,
startStepIndex,
startProjectData,
+ i18n,
},
ref
) => {
@@ -764,10 +766,39 @@ const InAppTutorialOrchestrator = React.forwardRef<
}
};
+ const getPreviewMessage = (): {|
+ message: string,
+ position: string,
+ |} | null => {
+ const { nextStepTrigger } = currentStep;
+ if (!nextStepTrigger || !nextStepTrigger.previewLaunched) return null;
+
+ const messageToUse = isTouchScreen
+ ? nextStepTrigger.inGameTouchMessage || nextStepTrigger.inGameMessage
+ : nextStepTrigger.inGameMessage;
+
+ const message = messageToUse
+ ? translateAndInterpolateText({
+ text: messageToUse,
+ data,
+ i18n,
+ project,
+ }) || null
+ : null;
+ if (message) {
+ return {
+ message,
+ position: nextStepTrigger.inGameMessagePosition || 'bottom-left',
+ };
+ }
+ return null;
+ };
+
React.useImperativeHandle(ref, () => ({
onPreviewLaunch,
getProgress,
| newIDE/app/src/InAppTutorial/InAppTutorialOrchestrator.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Add possibility to display message in the preview when an in-app tutorial is running | 7,379 | 4ian/GDevelop | 10,154 | JavaScript | AlexandreSi | |
// Center the model.
const centerPoint = this._model3DRuntimeObject._centerPoint;
if (centerPoint) {
threeObject.position.set(
-(boundingBox.min.x + modelWidth * centerPoint[0]),
// The model is flipped on Y axis.
-(boundingBox.min.y + modelHeight * (1 - centerPoint[1])),
-(boundingBox.min.z + modelDepth * centerPoint[2])
);
}
// Rotate the model.
threeObject.scale.set(1, 1, 1);
threeObject.rotation.set(
gdjs.toRad(rotationX),
gdjs.toRad(rotationY),
gdjs.toRad(rotationZ)
);
// Stretch the model in a 1x1x1 cube.
const scaleX = modelWidth < epsilon ? 1 : 1 / modelWidth;
const scaleY = modelHeight < epsilon ? 1 : 1 / modelHeight;
const scaleZ = modelDepth < epsilon ? 1 : 1 / modelDepth;
const scaleMatrix = new THREE.Matrix4();
// Flip on Y because the Y axis is on the opposite side of direct basis.
// It avoids models to be like a mirror refection.
scaleMatrix.makeScale(scaleX, -scaleY, scaleZ);
threeObject.updateMatrix();
threeObject.applyMatrix4(scaleMatrix);
if (keepAspectRatio) {
// Reduce the object dimensions to keep aspect ratio.
const widthRatio =
modelWidth < epsilon
? Number.POSITIVE_INFINITY
: originalWidth / modelWidth;
const heightRatio =
modelHeight < epsilon
? Number.POSITIVE_INFINITY
: originalHeight / modelHeight;
const depthRatio =
modelDepth < epsilon
? Number.POSITIVE_INFINITY
: originalDepth / modelDepth;
let scaleRatio = Math.min(widthRatio, heightRatio, depthRatio);
if (!Number.isFinite(scaleRatio)) {
scaleRatio = 1;
}
this._object._setOriginalWidth(scaleRatio * modelWidth); | No issues found. | // Center the model.
const centerPoint = this._model3DRuntimeObject._centerPoint;
if (centerPoint) {
threeObject.position.set(
-(boundingBox.min.x + modelWidth * centerPoint[0]),
// The model is flipped on Y axis.
-(boundingBox.min.y + modelHeight * (1 - centerPoint[1])),
-(boundingBox.min.z + modelDepth * centerPoint[2])
);
}
// Rotate the model.
threeObject.scale.set(1, 1, 1);
threeObject.rotation.set(
gdjs.toRad(rotationX),
gdjs.toRad(rotationY),
gdjs.toRad(rotationZ)
);
// Stretch the model in a 1x1x1 cube.
const scaleX = modelWidth < epsilon ? 1 : 1 / modelWidth;
const scaleY = modelHeight < epsilon ? 1 : 1 / modelHeight;
const scaleZ = modelDepth < epsilon ? 1 : 1 / modelDepth;
const scaleMatrix = new THREE.Matrix4();
// Flip on Y because the Y axis is on the opposite side of direct basis.
// It avoids models to be like a mirror refection.
scaleMatrix.makeScale(scaleX, -scaleY, scaleZ);
threeObject.updateMatrix();
threeObject.applyMatrix4(scaleMatrix);
if (keepAspectRatio) {
// Reduce the object dimensions to keep aspect ratio.
const widthRatio =
modelWidth < epsilon
? Number.POSITIVE_INFINITY
: originalWidth / modelWidth;
const heightRatio =
modelHeight < epsilon
? Number.POSITIVE_INFINITY
: originalHeight / modelHeight;
const depthRatio =
modelDepth < epsilon
? Number.POSITIVE_INFINITY
: originalDepth / modelDepth;
let scaleRatio = Math.min(widthRatio, heightRatio, depthRatio);
if (!Number.isFinite(scaleRatio)) {
scaleRatio = 1;
}
this._object._setOriginalWidth(scaleRatio * modelWidth); | @@ -359,7 +359,6 @@ namespace gdjs {
}
playAnimation(animationName: string, shouldLoop: boolean) {
- this._animationMixer.stopAllAction();
const clip = THREE.AnimationClip.findByName(
this._originalModel.animations,
animationName
@@ -370,12 +369,22 @@ namespace gdjs {
);
return;
}
+ const previousAction = this._action;
this._action = this._animationMixer.clipAction(clip);
this._action.setLoop(
shouldLoop ? THREE.LoopRepeat : THREE.LoopOnce,
Number.POSITIVE_INFINITY
);
this._action.clampWhenFinished = true;
+
+ if (previousAction && previousAction !== this._action) {
+ this._action.enabled = true;
+ this._action.crossFadeFrom(
+ previousAction,
+ this._model3DRuntimeObject._crossfadeDuration,
+ false
+ );
+ }
this._action.play();
// Make sure the first frame is displayed.
this._animationMixer.update(0); | Extensions/3D/Model3DRuntimeObject3DRenderer.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | add a crossfade duration property to 3d models and an action to set it | 7,386 | 4ian/GDevelop | 10,154 | JavaScript | NeylMahfouf2608 | |
);
const moveAnimation = React.useCallback(
(targetIndex: number) => {
const draggedIndex = draggedAnimationIndex.current;
if (draggedIndex === null) return;
setNameErrors({});
model3DConfiguration.moveAnimation(
draggedIndex,
targetIndex > draggedIndex ? targetIndex - 1 : targetIndex
);
forceUpdate();
},
[model3DConfiguration, forceUpdate]
);
const changeAnimationName = React.useCallback(
(animationIndex, newName) => {
const currentName = model3DConfiguration
.getAnimation(animationIndex)
.getName();
if (currentName === newName) return;
const animation = model3DConfiguration.getAnimation(animationIndex);
setNameErrors({});
if (newName !== '' && model3DConfiguration.hasAnimationNamed(newName)) {
// The indexes can be used as a key because errors are cleared when
// animations are moved.
setNameErrors({
...nameErrors,
[animationIndex]: (
<Trans>The animation name {newName} is already taken</Trans>
),
});
return;
}
animation.setName(newName);
if (object) {
if (layout) {
gd.WholeProjectRefactorer.renameObjectAnimationInScene(
project,
layout,
object,
currentName,
newName
);
} else if (eventsFunctionsExtension && eventsBasedObject) { | No issues found. | );
const moveAnimation = React.useCallback(
(targetIndex: number) => {
const draggedIndex = draggedAnimationIndex.current;
if (draggedIndex === null) return;
setNameErrors({});
model3DConfiguration.moveAnimation(
draggedIndex,
targetIndex > draggedIndex ? targetIndex - 1 : targetIndex
);
forceUpdate();
},
[model3DConfiguration, forceUpdate]
);
const changeAnimationName = React.useCallback(
(animationIndex, newName) => {
const currentName = model3DConfiguration
.getAnimation(animationIndex)
.getName();
if (currentName === newName) return;
const animation = model3DConfiguration.getAnimation(animationIndex);
setNameErrors({});
if (newName !== '' && model3DConfiguration.hasAnimationNamed(newName)) {
// The indexes can be used as a key because errors are cleared when
// animations are moved.
setNameErrors({
...nameErrors,
[animationIndex]: (
<Trans>The animation name {newName} is already taken</Trans>
),
});
return;
}
animation.setName(newName);
if (object) {
if (layout) {
gd.WholeProjectRefactorer.renameObjectAnimationInScene(
project,
layout,
object,
currentName,
newName
);
} else if (eventsFunctionsExtension && eventsBasedObject) { | @@ -667,6 +667,12 @@ const Model3DEditor = ({
</SelectField>
</ResponsiveLineStackLayout>
<Text size="block-title">Animations</Text>
+ <Column noMargin expand>
+ <PropertyField
+ objectConfiguration={objectConfiguration}
+ propertyName="crossfadeDuration"
+ />
+ </Column>
<Column noMargin expand useFullHeight>
{model3DConfiguration.getAnimationsCount() === 0 ? (
<Column noMargin expand justifyContent="center"> | newIDE/app/src/ObjectEditor/Editors/Model3DEditor.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | fix crossfade icon, crossfade property and add unit | 7,390 | 4ian/GDevelop | 10,154 | JavaScript | NeylMahfouf2608 | |
namespace gdjs {
export namespace evtTools {
export namespace spatialSound {
export const setSoundPosition = (
instanceContainer: gdjs.RuntimeInstanceContainer,
channel: integer,
x: float,
y: float,
z: float
) => {
// TODO EBO The position must be transform to the scene position when it comes from a custom object.
const soundManager = instanceContainer.getScene().getSoundManager();
soundManager.setSoundSpatialPositionOnChannel(channel, x, y, z);
};
}
}
}
| No issues found. | namespace gdjs {
export namespace evtTools {
export namespace spatialSound {
export const setSoundPosition = (
instanceContainer: gdjs.RuntimeInstanceContainer,
channel: integer,
x: float,
y: float,
z: float
) => {
// TODO EBO The position must be transform to the scene position when it comes from a custom object.
const soundManager = instanceContainer.getScene().getSoundManager();
soundManager.setSoundSpatialPositionOnChannel(channel, x, y, z);
};
}
}
}
| @@ -1,7 +1,6 @@
namespace gdjs {
export namespace evtTools {
export namespace spatialSound {
- const logger = new gdjs.Logger('Spatial Sound');
export const setSoundPosition = (
instanceContainer: gdjs.RuntimeInstanceContainer,
channel: integer,
@@ -10,15 +9,8 @@ namespace gdjs {
z: float
) => {
// TODO EBO The position must be transform to the scene position when it comes from a custom object.
- const sound = instanceContainer
- .getScene()
- .getSoundManager()
- .getSoundOnChannel(channel);
- if (sound) sound.setSpatialPosition(x, y, z);
- else
- logger.error(
- `Cannot set the spatial position of a non-existing sound on channel ${channel}.`
- );
+ const soundManager = instanceContainer.getScene().getSoundManager();
+ soundManager.setSoundSpatialPositionOnChannel(channel, x, y, z);
};
}
} | Extensions/SpatialSound/spatialsoundtools.ts | 0 | TypeScript | 1 | none | 16 | 18 | 18 | true | Fix spatial sound setting if sound not playing yet | 7,393 | 4ian/GDevelop | 10,154 | JavaScript | AlexandreSi | |
*
* This is an Euler angle. Objects use the `ZYX` order.
*/
setRotationY(angle: float): void {
this._rotationY = angle;
this.getRenderer().updateRotation();
}
/**
* Get the object rotation on the X axis.
*
* This is an Euler angle. Objects use the `ZYX` order.
*/
getRotationX(): float {
return this._rotationX;
}
/**
* Get the object rotation on the Y axis.
*
* This is an Euler angle. Objects use the `ZYX` order.
*/
getRotationY(): float {
return this._rotationY;
}
/**
* Turn the object around the scene x axis at its center.
* @param deltaAngle the rotation angle
*/
turnAroundX(deltaAngle: float): void {
const axisX = gdjs.RuntimeObject3D._temporaryVector;
axisX.set(1, 0, 0);
const mesh = this.getRenderer().get3DRendererObject();
mesh.rotateOnWorldAxis(axisX, gdjs.toRad(deltaAngle));
this._rotationX = gdjs.toDegrees(mesh.rotation.x);
this._rotationY = gdjs.toDegrees(mesh.rotation.y);
this.setAngle(gdjs.toDegrees(mesh.rotation.z));
}
/**
* Turn the object around the scene y axis at its center.
* @param deltaAngle the rotation angle
*/
turnAroundY(deltaAngle: float): void {
const axisY = gdjs.RuntimeObject3D._temporaryVector;
axisY.set(0, 1, 0);
const mesh = this.getRenderer().get3DRendererObject();
mesh.rotateOnWorldAxis(axisY, gdjs.toRad(deltaAngle)); | No issues found. | *
* This is an Euler angle. Objects use the `ZYX` order.
*/
setRotationY(angle: float): void {
this._rotationY = angle;
this.getRenderer().updateRotation();
}
/**
* Get the object rotation on the X axis.
*
* This is an Euler angle. Objects use the `ZYX` order.
*/
getRotationX(): float {
return this._rotationX;
}
/**
* Get the object rotation on the Y axis.
*
* This is an Euler angle. Objects use the `ZYX` order.
*/
getRotationY(): float {
return this._rotationY;
}
/**
* Turn the object around the scene x axis at its center.
* @param deltaAngle the rotation angle
*/
turnAroundX(deltaAngle: float): void {
const axisX = gdjs.RuntimeObject3D._temporaryVector;
axisX.set(1, 0, 0);
const mesh = this.getRenderer().get3DRendererObject();
mesh.rotateOnWorldAxis(axisX, gdjs.toRad(deltaAngle));
this._rotationX = gdjs.toDegrees(mesh.rotation.x);
this._rotationY = gdjs.toDegrees(mesh.rotation.y);
this.setAngle(gdjs.toDegrees(mesh.rotation.z));
}
/**
* Turn the object around the scene y axis at its center.
* @param deltaAngle the rotation angle
*/
turnAroundY(deltaAngle: float): void {
const axisY = gdjs.RuntimeObject3D._temporaryVector;
axisY.set(0, 1, 0);
const mesh = this.getRenderer().get3DRendererObject();
mesh.rotateOnWorldAxis(axisY, gdjs.toRad(deltaAngle)); | @@ -1,15 +1,4 @@
namespace gdjs {
- export interface Object3DDataContent {
- width: float;
- height: float;
- depth: float;
- }
- /** Base parameters for {@link gdjs.RuntimeObject3D} */
- export interface Object3DData extends ObjectData {
- /** The base parameters of the RuntimeObject3D */
- content: Object3DDataContent;
- }
-
const getValidDimensionValue = (value: float | undefined) =>
value === undefined ? 100 : value <= 0 ? 1 : value;
@@ -84,7 +73,7 @@ namespace gdjs {
constructor(
instanceContainer: gdjs.RuntimeInstanceContainer,
- objectData: Object3DData
+ objectData: gdjs.Object3DData
) {
super(instanceContainer, objectData);
// TODO Should 0 be replaced by 0.01 instead of using the default value? | Extensions/3D/A_RuntimeObject3D.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | Upgrade to TypeScript 5.4.5 | 7,394 | 4ian/GDevelop | 10,154 | JavaScript | D8H | |
else {
// Between MAXIMUM_DURATION_FOR_SMALL_STATUS and MINIMUM_DURATION_FOR_RISKY_STATUS without saving.
if (changesCount <= MINIMUM_CHANGES_FOR_SIGNIFICANT_STATUS) return 'small';
if (changesCount <= MINIMUM_CHANGES_FOR_RISKY_STATUS) return 'significant';
return 'risky';
}
};
const useSaveReminder = ({
onSave,
project,
isInQuickCustomization,
}: Props) => {
const unsavedChanges = React.useContext(UnsavedChangesContext);
const { currentlyRunningInAppTutorial } = React.useContext(
InAppTutorialContext
);
const {
values: { displaySaveReminder: displaySaveReminderPreference },
} = React.useContext(PreferencesContext);
const [displayReminder, setDisplayReminder] = React.useState<boolean>(false);
const [lastAcknowledgement, setLastAcknowledgement] = React.useState<
number | null
>(null);
useInterval(
() => {
const unsavedChangesAmount = getUnsavedChangesAmount(unsavedChanges);
if (
!displaySaveReminderPreference.activated ||
isInQuickCustomization ||
currentlyRunningInAppTutorial ||
!project
) {
setDisplayReminder(false);
return;
}
const now = Date.now();
const newDisplayReminder =
unsavedChangesAmount === 'risky' &&
(!lastAcknowledgement ||
now - lastAcknowledgement > DURATION_BETWEEN_TWO_DISPLAYS);
if (newDisplayReminder !== displayReminder) {
setDisplayReminder(newDisplayReminder);
}
},
project ? CHECK_FREQUENCY : null
);
const onHideReminder = React.useCallback(() => { | No issues found. | else {
// Between MAXIMUM_DURATION_FOR_SMALL_STATUS and MINIMUM_DURATION_FOR_RISKY_STATUS without saving.
if (changesCount <= MINIMUM_CHANGES_FOR_SIGNIFICANT_STATUS) return 'small';
if (changesCount <= MINIMUM_CHANGES_FOR_RISKY_STATUS) return 'significant';
return 'risky';
}
};
const useSaveReminder = ({
onSave,
project,
isInQuickCustomization,
}: Props) => {
const unsavedChanges = React.useContext(UnsavedChangesContext);
const { currentlyRunningInAppTutorial } = React.useContext(
InAppTutorialContext
);
const {
values: { displaySaveReminder: displaySaveReminderPreference },
} = React.useContext(PreferencesContext);
const [displayReminder, setDisplayReminder] = React.useState<boolean>(false);
const [lastAcknowledgement, setLastAcknowledgement] = React.useState<
number | null
>(null);
useInterval(
() => {
const unsavedChangesAmount = getUnsavedChangesAmount(unsavedChanges);
if (
!displaySaveReminderPreference.activated ||
isInQuickCustomization ||
currentlyRunningInAppTutorial ||
!project
) {
setDisplayReminder(false);
return;
}
const now = Date.now();
const newDisplayReminder =
unsavedChangesAmount === 'risky' &&
(!lastAcknowledgement ||
now - lastAcknowledgement > DURATION_BETWEEN_TWO_DISPLAYS);
if (newDisplayReminder !== displayReminder) {
setDisplayReminder(newDisplayReminder);
}
},
project ? CHECK_FREQUENCY : null
);
const onHideReminder = React.useCallback(() => { | @@ -28,16 +28,19 @@ const CHECK_FREQUENCY = 5000;
export const getUnsavedChangesAmount = (
unsavedChanges: UnsavedChanges
): UnsavedChangesAmount => {
- const { getChangesCount, getLastCheckpointTime } = unsavedChanges;
+ const { getChangesCount, getTimeOfFirstChangeSinceLastSave } = unsavedChanges;
const changesCount = getChangesCount();
- const lastCheckpointTime = getLastCheckpointTime();
+ const timeOfFirstChangeSinceLastSave = getTimeOfFirstChangeSinceLastSave();
- if (changesCount === 0 || !lastCheckpointTime) return 'none';
+ if (changesCount === 0 || !timeOfFirstChangeSinceLastSave) return 'none';
const now = Date.now();
if (changesCount > MINIMUM_CHANGES_FOR_RISKY_STATUS) return 'risky';
- if (now - lastCheckpointTime > MINIMUM_DURATION_FOR_RISKY_STATUS)
+ if (now - timeOfFirstChangeSinceLastSave > MINIMUM_DURATION_FOR_RISKY_STATUS)
return 'risky';
- else if (now - lastCheckpointTime < MAXIMUM_DURATION_FOR_SMALL_STATUS)
+ else if (
+ now - timeOfFirstChangeSinceLastSave <
+ MAXIMUM_DURATION_FOR_SMALL_STATUS
+ )
return 'small';
else {
// Between MAXIMUM_DURATION_FOR_SMALL_STATUS and MINIMUM_DURATION_FOR_RISKY_STATUS without saving.
@@ -102,6 +105,17 @@ const useSaveReminder = ({
[onSave]
);
+ React.useEffect(
+ () => {
+ if (!project) {
+ setLastAcknowledgement(null);
+ setDisplayReminder(false);
+ }
+ },
+ // If project is closed while the reminder is displayed, close it.
+ [project]
+ );
+
const renderSaveReminder = React.useCallback(
() => {
return ( | newIDE/app/src/MainFrame/UseSaveReminder.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Improve save reminder | 7,413 | 4ian/GDevelop | 10,154 | JavaScript | AlexandreSi | |
const shouldAllowCreatingProject =
!isLoading &&
!needUserAuthenticationForStorage &&
!hasTooManyCloudProjects &&
(hasSelectedAStorageProvider || shouldAllowCreatingProjectWithoutSaving);
const onCreateGameClick = React.useCallback(
async (i18n: I18nType) => {
if (!shouldAllowCreatingProject) return;
setProjectNameError(null);
if (!projectName) {
setProjectNameError(
<Trans>Please enter a name for your project.</Trans>
);
return;
}
// Make sure that the path is up to date with the project name.
const projectLocation = storageProvider.getProjectLocation
? storageProvider.getProjectLocation({
projectName,
saveAsLocation,
newProjectsDefaultFolder,
})
: saveAsLocation;
const projectSetup = {
projectName,
storageProvider,
saveAsLocation: projectLocation,
height: selectedHeight,
width: selectedWidth,
orientation: selectedOrientation,
optimizeForPixelArt,
};
if (selectedExampleShortHeader) {
await onCreateFromExample(
selectedExampleShortHeader,
{
// We only pass down the project name as this is the only customizable field for an example.
projectName,
storageProvider,
saveAsLocation: projectLocation,
},
i18n
);
} else if (selectedPrivateGameTemplateListingData) {
await onCreateProjectFromPrivateGameTemplate(
selectedPrivateGameTemplateListingData, | No issues found. | const shouldAllowCreatingProject =
!isLoading &&
!needUserAuthenticationForStorage &&
!hasTooManyCloudProjects &&
(hasSelectedAStorageProvider || shouldAllowCreatingProjectWithoutSaving);
const onCreateGameClick = React.useCallback(
async (i18n: I18nType) => {
if (!shouldAllowCreatingProject) return;
setProjectNameError(null);
if (!projectName) {
setProjectNameError(
<Trans>Please enter a name for your project.</Trans>
);
return;
}
// Make sure that the path is up to date with the project name.
const projectLocation = storageProvider.getProjectLocation
? storageProvider.getProjectLocation({
projectName,
saveAsLocation,
newProjectsDefaultFolder,
})
: saveAsLocation;
const projectSetup = {
projectName,
storageProvider,
saveAsLocation: projectLocation,
height: selectedHeight,
width: selectedWidth,
orientation: selectedOrientation,
optimizeForPixelArt,
};
if (selectedExampleShortHeader) {
await onCreateFromExample(
selectedExampleShortHeader,
{
// We only pass down the project name as this is the only customizable field for an example.
projectName,
storageProvider,
saveAsLocation: projectLocation,
},
i18n
);
} else if (selectedPrivateGameTemplateListingData) {
await onCreateProjectFromPrivateGameTemplate(
selectedPrivateGameTemplateListingData, | @@ -39,6 +39,7 @@ import { type PrivateGameTemplateListingData } from '../Utils/GDevelopServices/S
import { CLOUD_PROJECT_NAME_MAX_LENGTH } from '../Utils/GDevelopServices/Project';
import AIPromptField from './AIPromptField';
import EmptyAndStartingPointProjects, {
+ isLinkedToStartingPointExampleShortHeader,
isStartingPointExampleShortHeader,
} from './EmptyAndStartingPointProjects';
import TextButton from '../UI/TextButton';
@@ -55,6 +56,7 @@ import { PrivateGameTemplateStoreContext } from '../AssetStore/PrivateGameTempla
import { getUserProductPurchaseUsageType } from '../AssetStore/ProductPageHelper';
import { useOnlineStatus } from '../Utils/OnlineStatus';
import PrivateGameTemplateOwnedInformationPage from '../AssetStore/PrivateGameTemplates/PrivateGameTemplateOwnedInformationPage';
+import { ExampleStoreContext } from '../AssetStore/ExampleStore/ExampleStoreContext';
const electron = optionalRequire('electron');
const remote = optionalRequire('@electron/remote');
@@ -141,6 +143,7 @@ const NewProjectSetupDialog = ({
emptyProjectSelected,
setEmptyProjectSelected,
] = React.useState<boolean>(false);
+ const { exampleShortHeaders } = React.useContext(ExampleStoreContext);
const isOnHomePage =
!selectedExampleShortHeader &&
!selectedPrivateGameTemplateListingData &&
@@ -253,6 +256,83 @@ const NewProjectSetupDialog = ({
const isLoading = isGeneratingProject || isProjectOpening;
+ const linkedExampleShortHeaders: {
+ exampleShortHeader: ExampleShortHeader,
+ relation: string,
+ }[] = React.useMemo(
+ () => {
+ if (
+ !exampleShortHeaders ||
+ !selectedExampleShortHeader ||
+ !selectedExampleShortHeader.linkedExampleShortHeaders
+ )
+ return [];
+
+ return selectedExampleShortHeader.linkedExampleShortHeaders
+ .map(({ slug, relation }) => {
+ const linkedExampleShortHeader = exampleShortHeaders.find(
+ exampleShortHeader => exampleShortH | newIDE/app/src/ProjectCreation/NewProjectSetupDialog.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Allow selecting a Pixel Art version of 2D starting points | 7,425 | 4ian/GDevelop | 10,154 | JavaScript | ClementPasteau | |
gd::String conditionsCode = codeGenerator.GenerateConditionsListCode(
event.GetConditions(), context);
gd::String actionsCode =
codeGenerator.GenerateActionsListCode(event.GetActions(), context);
gd::String ifPredicate = event.GetConditions().empty()
? "true"
: codeGenerator.GenerateBooleanFullName(
"isConditionTrue", context);
// Prepare object declaration and sub events
gd::String subevents =
codeGenerator.GenerateEventsListCode(event.GetSubEvents(), context);
gd::String objectDeclaration =
codeGenerator.GenerateObjectsDeclarationCode(context) + "\n";
// Write final code
gd::String structureChildVariableName =
"structureChildVariable" +
gd::String::From(context.GetContextDepth());
gd::String iterableReferenceVariableName =
"iterableReference" + gd::String::From(context.GetContextDepth());
gd::String iteratorKeyVariableName =
"iteratorKey" + gd::String::From(context.GetContextDepth());
bool valueIteratorExists =
!event.GetValueIteratorVariableName().empty();
bool keyIteratorExists = !event.GetKeyIteratorVariableName().empty();
// clang-format off
// Define references to variables (if they exist)
if (keyIteratorExists)
outputCode +=
"const $KEY_ITERATOR_REFERENCE = "
"$KEY_ITERATOR_VARIABLE_ACCESSOR;\n";
if (valueIteratorExists)
outputCode +=
"const $VALUE_ITERATOR_REFERENCE = "
"$VALUE_ITERATOR_VARIABLE_ACCESSOR;\n";
outputCode +=
"const $ITERABLE_REFERENCE = $ITERABLE_VARIABLE_ACCESSOR;\n";
// Do not execute the loop on non iterables
outputCode += "if(!$ITERABLE_REFERENCE.isPrimitive()) {\n";
// Begin the for loop
outputCode +=
"for(\n"
" const $ITERATOR_KEY in \n"
" $ITERABLE_REFERENCE.getType() === \"structure\"\n"
" ? $ITERABLE_REFERENCE.getAllChildren()\n"
" : $ITERABLE_REFERENCE.getType() === \"array\"\n" | No issues found. | gd::String conditionsCode = codeGenerator.GenerateConditionsListCode(
event.GetConditions(), context);
gd::String actionsCode =
codeGenerator.GenerateActionsListCode(event.GetActions(), context);
gd::String ifPredicate = event.GetConditions().empty()
? "true"
: codeGenerator.GenerateBooleanFullName(
"isConditionTrue", context);
// Prepare object declaration and sub events
gd::String subevents =
codeGenerator.GenerateEventsListCode(event.GetSubEvents(), context);
gd::String objectDeclaration =
codeGenerator.GenerateObjectsDeclarationCode(context) + "\n";
// Write final code
gd::String structureChildVariableName =
"structureChildVariable" +
gd::String::From(context.GetContextDepth());
gd::String iterableReferenceVariableName =
"iterableReference" + gd::String::From(context.GetContextDepth());
gd::String iteratorKeyVariableName =
"iteratorKey" + gd::String::From(context.GetContextDepth());
bool valueIteratorExists =
!event.GetValueIteratorVariableName().empty();
bool keyIteratorExists = !event.GetKeyIteratorVariableName().empty();
// clang-format off
// Define references to variables (if they exist)
if (keyIteratorExists)
outputCode +=
"const $KEY_ITERATOR_REFERENCE = "
"$KEY_ITERATOR_VARIABLE_ACCESSOR;\n";
if (valueIteratorExists)
outputCode +=
"const $VALUE_ITERATOR_REFERENCE = "
"$VALUE_ITERATOR_VARIABLE_ACCESSOR;\n";
outputCode +=
"const $ITERABLE_REFERENCE = $ITERABLE_VARIABLE_ACCESSOR;\n";
// Do not execute the loop on non iterables
outputCode += "if(!$ITERABLE_REFERENCE.isPrimitive()) {\n";
// Begin the for loop
outputCode +=
"for(\n"
" const $ITERATOR_KEY in \n"
" $ITERABLE_REFERENCE.getType() === \"structure\"\n"
" ? $ITERABLE_REFERENCE.getAllChildren()\n"
" : $ITERABLE_REFERENCE.getType() === \"array\"\n" | @@ -540,7 +540,7 @@ CommonInstructionsExtension::CommonInstructionsExtension() {
.FindAndReplace(
"$VALUE_ITERATOR_VARIABLE_ACCESSOR",
codeGenerator.GenerateAnyOrSceneVariableGetter(
- event.GetValueIteratorVariableName(), context))
+ event.GetValueIteratorVariableName(), parentContext))
.FindAndReplace("$VALUE_ITERATOR_REFERENCE",
iteratorReferenceVariableName);
}
@@ -554,7 +554,7 @@ CommonInstructionsExtension::CommonInstructionsExtension() {
.FindAndReplace(
"$KEY_ITERATOR_VARIABLE_ACCESSOR",
codeGenerator.GenerateAnyOrSceneVariableGetter(
- event.GetKeyIteratorVariableName(), context))
+ event.GetKeyIteratorVariableName(), parentContext))
.FindAndReplace("$KEY_ITERATOR_REFERENCE",
iteratorReferenceVariableName);
}
@@ -567,7 +567,7 @@ CommonInstructionsExtension::CommonInstructionsExtension() {
iterableReferenceVariableName)
.FindAndReplace("$ITERABLE_VARIABLE_ACCESSOR",
codeGenerator.GenerateAnyOrSceneVariableGetter(
- event.GetIterableVariableName(), context));
+ event.GetIterableVariableName(), parentContext));
});
GetAllEvents()["BuiltinCommonInstructions::Repeat"].SetCodeGenerator( | GDJS/GDJS/Extensions/Builtin/CommonInstructionsExtension.cpp | 0 | C++ | 1 | none | 16 | 51 | 51 | true | Fix access to object in variable expressions of "for each child variable" loops | 7,435 | 4ian/GDevelop | 10,154 | JavaScript | D8H | |
) {
return null;
}
return (
<DragSourceAndDropTarget
key={property.ptr}
beginDrag={() => {
draggedProperty.current = property;
return {};
}}
canDrag={() => true}
canDrop={() => true}
drop={() => {
movePropertyBefore(property);
}}
>
{({
connectDragSource,
connectDropTarget,
isOver,
canDrop,
}) =>
connectDropTarget(
<div
key={property.ptr}
style={styles.rowContainer}
>
{isOver && <DropIndicator canDrop={canDrop} />}
<div
ref={propertyRef}
style={{
...styles.rowContent,
backgroundColor:
gdevelopTheme.list.itemsBackgroundColor,
}}
>
{connectDragSource(
<span>
<Column>
<DragHandleIcon />
</Column>
</span>
)}
<ResponsiveLineStackLayout expand noMargin>
<Line noMargin expand alignItems="center">
<SemiControlledTextField
margin="none"
commitOnBlur
translatableHintText={t`Enter the property name`}
value={property.getName()} | No issues found. | ) {
return null;
}
return (
<DragSourceAndDropTarget
key={property.ptr}
beginDrag={() => {
draggedProperty.current = property;
return {};
}}
canDrag={() => true}
canDrop={() => true}
drop={() => {
movePropertyBefore(property);
}}
>
{({
connectDragSource,
connectDropTarget,
isOver,
canDrop,
}) =>
connectDropTarget(
<div
key={property.ptr}
style={styles.rowContainer}
>
{isOver && <DropIndicator canDrop={canDrop} />}
<div
ref={propertyRef}
style={{
...styles.rowContent,
backgroundColor:
gdevelopTheme.list.itemsBackgroundColor,
}}
>
{connectDragSource(
<span>
<Column>
<DragHandleIcon />
</Column>
</span>
)}
<ResponsiveLineStackLayout expand noMargin>
<Line noMargin expand alignItems="center">
<SemiControlledTextField
margin="none"
commitOnBlur
translatableHintText={t`Enter the property name`}
value={property.getName()} | @@ -734,6 +734,11 @@ export default function EventsBasedObjectPropertiesEditor({
value="LeaderboardId"
label={t`Leaderboard (text)`}
/>
+ <SelectOption
+ key="property-type-text-area"
+ value="MultilineString"
+ label={t`Multiline text`}
+ />
<SelectOption
key="property-type-resource"
value="Resource"
@@ -786,7 +791,9 @@ export default function EventsBasedObjectPropertiesEditor({
</SelectField>
)}
{(property.getType() === 'String' ||
- property.getType() === 'Number') && (
+ property.getType() === 'Number' ||
+ property.getType() ===
+ 'MultilineString') && (
<SemiControlledTextField
commitOnBlur
floatingLabelText={
@@ -804,6 +811,10 @@ export default function EventsBasedObjectPropertiesEditor({
onPropertiesUpdated &&
onPropertiesUpdated();
}}
+ multiline={
+ property.getType() ===
+ 'MultilineString'
+ }
| newIDE/app/src/EventsBasedObjectEditor/EventsBasedObjectPropertiesEditor.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Allow custom objects to declare multi-line text properties | 7,436 | 4ian/GDevelop | 10,154 | JavaScript | D8H | |
// Resources may have been renamed to be added to the project.
// In this case, rename them in the object.
const renamedResourcesMap = toNewGdMapStringString(resourceNewNames);
const resourcesRenamer = new gd.ResourcesRenamer(
project.getResourcesManager(),
renamedResourcesMap
);
renamedResourcesMap.delete();
object.getConfiguration().exposeResources(resourcesRenamer);
resourcesRenamer.delete();
createdObjects.push(object);
});
return {
createdObjects,
};
};
export const installPublicAsset = addAssetToProject;
export type RequiredExtension = {|
extensionName: string,
extensionVersion: string,
|};
export const getRequiredExtensionsFromAsset = (
asset: Asset
): Array<RequiredExtension> => {
return uniqBy(
flatten(
asset.objectAssets.map(
objectAsset => objectAsset.requiredExtensions || []
)
),
({ extensionName }) => extensionName
);
};
const filterMissingExtensions = (
gd: libGDevelop,
requiredExtensions: Array<ExtensionShortHeader>
): Array<ExtensionShortHeader> => {
const loadedExtensionNames = mapVector(
gd.asPlatform(gd.JsPlatform.get()).getAllPlatformExtensions(),
extension => {
return extension.getName();
}
);
return requiredExtensions.filter(extension => { | No issues found. | // Resources may have been renamed to be added to the project.
// In this case, rename them in the object.
const renamedResourcesMap = toNewGdMapStringString(resourceNewNames);
const resourcesRenamer = new gd.ResourcesRenamer(
project.getResourcesManager(),
renamedResourcesMap
);
renamedResourcesMap.delete();
object.getConfiguration().exposeResources(resourcesRenamer);
resourcesRenamer.delete();
createdObjects.push(object);
});
return {
createdObjects,
};
};
export const installPublicAsset = addAssetToProject;
export type RequiredExtension = {|
extensionName: string,
extensionVersion: string,
|};
export const getRequiredExtensionsFromAsset = (
asset: Asset
): Array<RequiredExtension> => {
return uniqBy(
flatten(
asset.objectAssets.map(
objectAsset => objectAsset.requiredExtensions || []
)
),
({ extensionName }) => extensionName
);
};
const filterMissingExtensions = (
gd: libGDevelop,
requiredExtensions: Array<ExtensionShortHeader>
): Array<ExtensionShortHeader> => {
const loadedExtensionNames = mapVector(
gd.asPlatform(gd.JsPlatform.get()).getAllPlatformExtensions(),
extension => {
return extension.getName();
}
);
return requiredExtensions.filter(extension => { | @@ -4,7 +4,9 @@ import {
isPixelArt,
isPublicAssetResourceUrl,
extractDecodedFilenameWithExtensionFromPublicAssetResourceUrl,
+ isCompatibleWithGDevelopVersion,
} from '../Utils/GDevelopServices/Asset';
+import { getIDEVersion } from '../Version';
import newNameGenerator from '../Utils/NewNameGenerator';
import { unserializeFromJSObject } from '../Utils/Serializer';
import flatten from 'lodash/flatten';
@@ -273,6 +275,7 @@ export type RequiredExtensionInstallation = {|
requiredExtensionShortHeaders: Array<ExtensionShortHeader>,
missingExtensionShortHeaders: Array<ExtensionShortHeader>,
outOfDateExtensionShortHeaders: Array<ExtensionShortHeader>,
+ incompatibleWithIdeExtensionShortHeaders: Array<ExtensionShortHeader>,
|};
export type InstallRequiredExtensionsArgs = {|
@@ -390,6 +393,7 @@ export const checkRequiredExtensionsUpdate = async ({
requiredExtensionShortHeaders: [],
missingExtensionShortHeaders: [],
outOfDateExtensionShortHeaders: [],
+ incompatibleWithIdeExtensionShortHeaders: [],
};
}
@@ -414,7 +418,24 @@ export const checkRequiredExtensionsUpdate = async ({
}
);
- const outOfDateExtensionShortHeaders = requiredExtensionShortHeaders.filter(
+ const compatibleWithIdeExtensionShortHeaders: Array<ExtensionShortHeader> = [];
+ const incompatibleWithIdeExtensionShortHeaders: Array<ExtensionShortHeader> = [];
+ for (const requiredExtensionShortHeader of requiredExtensionShortHeaders) {
+ if (
+ isCompatibleWithGDevelopVersion(
+ getIDEVersion(),
+ requiredExtensionShortHeader.gdevelopVersion
+ )
+ ) {
+ compatibleWithIdeExtensionShortHeaders.push(requiredExtensionShortHeader);
+ } else {
+ incompatibleWithIdeExtensionShortHeaders.push(
+ requiredExtensionShortHeader
+ );
+ }
+ }
+
+ const outOfDateExtensionShortHeaders = compatibleWithIdeExtensionShortHeaders.filter(
requiredExtensionShortHeader =>
project.hasEvent | newIDE/app/src/AssetStore/InstallAsset.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Forbid to install assets or behaviors from extensions incompatible with the editor | 7,441 | 4ian/GDevelop | 10,154 | JavaScript | D8H | |
// @flow
export const OPEN_OBJECTS_PANEL_BUTTON_ID = 'toolbar-open-objects-panel-button';
export const OPEN_OBJECT_GROUPS_PANEL_BUTTON_ID =
'toolbar-open-object-groups-panel-button';
export const OPEN_PROPERTIES_PANEL_BUTTON_ID =
'toolbar-open-properties-panel-button';
export const OPEN_INSTANCES_PANEL_BUTTON_ID =
'toolbar-open-instances-list-panel-button';
export const OPEN_LAYERS_PANEL_BUTTON_ID = 'toolbar-open-layers-panel-button';
export const TOOLBAR_COMMON_FORMATTED_BUTTON_IDS = [
`#${OPEN_OBJECTS_PANEL_BUTTON_ID}`,
`#${OPEN_OBJECT_GROUPS_PANEL_BUTTON_ID}`,
`#${OPEN_PROPERTIES_PANEL_BUTTON_ID}`,
`#${OPEN_INSTANCES_PANEL_BUTTON_ID}`,
`#${OPEN_LAYERS_PANEL_BUTTON_ID}`,
];
export type EditorId =
| 'objects-list'
| 'properties'
| 'object-groups-list'
| 'instances-list'
| 'layers-list';
| No issues found. | // @flow
export const OPEN_OBJECTS_PANEL_BUTTON_ID = 'toolbar-open-objects-panel-button';
export const OPEN_OBJECT_GROUPS_PANEL_BUTTON_ID =
'toolbar-open-object-groups-panel-button';
export const OPEN_PROPERTIES_PANEL_BUTTON_ID =
'toolbar-open-properties-panel-button';
export const OPEN_INSTANCES_PANEL_BUTTON_ID =
'toolbar-open-instances-list-panel-button';
export const OPEN_LAYERS_PANEL_BUTTON_ID = 'toolbar-open-layers-panel-button';
export const TOOLBAR_COMMON_FORMATTED_BUTTON_IDS = [
`#${OPEN_OBJECTS_PANEL_BUTTON_ID}`,
`#${OPEN_OBJECT_GROUPS_PANEL_BUTTON_ID}`,
`#${OPEN_PROPERTIES_PANEL_BUTTON_ID}`,
`#${OPEN_INSTANCES_PANEL_BUTTON_ID}`,
`#${OPEN_LAYERS_PANEL_BUTTON_ID}`,
];
export type EditorId =
| 'objects-list'
| 'properties'
| 'object-groups-list'
| 'instances-list'
| 'layers-list';
| @@ -0,0 +1,23 @@
+// @flow
+export const OPEN_OBJECTS_PANEL_BUTTON_ID = 'toolbar-open-objects-panel-button';
+export const OPEN_OBJECT_GROUPS_PANEL_BUTTON_ID =
+ 'toolbar-open-object-groups-panel-button';
+export const OPEN_PROPERTIES_PANEL_BUTTON_ID =
+ 'toolbar-open-properties-panel-button';
+export const OPEN_INSTANCES_PANEL_BUTTON_ID =
+ 'toolbar-open-instances-list-panel-button';
+export const OPEN_LAYERS_PANEL_BUTTON_ID = 'toolbar-open-layers-panel-button';
+export const TOOLBAR_COMMON_FORMATTED_BUTTON_IDS = [
+ `#${OPEN_OBJECTS_PANEL_BUTTON_ID}`,
+ `#${OPEN_OBJECT_GROUPS_PANEL_BUTTON_ID}`,
+ `#${OPEN_PROPERTIES_PANEL_BUTTON_ID}`,
+ `#${OPEN_INSTANCES_PANEL_BUTTON_ID}`,
+ `#${OPEN_LAYERS_PANEL_BUTTON_ID}`,
+];
+
+export type EditorId =
+ | 'objects-list'
+ | 'properties'
+ | 'object-groups-list'
+ | 'instances-list'
+ | 'layers-list'; | newIDE/app/src/SceneEditor/utils.js | 0 | JavaScript | 1 | none | 16 | 24 | 24 | true | Improve Guided Lessons flow by preventing clicking outside of the next action | 7,444 | 4ian/GDevelop | 10,154 | JavaScript | ClementPasteau | |
export const sendUserSurveyStarted = () => {
recordEvent('user_survey_started');
};
export const sendUserSurveyCompleted = () => {
recordEvent('user_survey_completed');
};
export const sendUserSurveyHidden = () => {
recordEvent('user_survey_hidden');
};
export const sendHelpSearch = (searchText: string) => {
recordEvent('help_search', {
searchText,
});
};
export const sendErrorMessage = (
message: string,
type:
| 'error'
| 'error-boundary_mainframe'
| 'error-boundary_list-search-result'
| 'error-boundary_box-search-result'
| 'error-boundary_app',
rawError: any,
errorId: string
) => {
recordEvent('error_message', {
message,
type,
rawError,
errorId,
});
};
export const sendSignupDone = (email: string) => {
recordEvent('signup', {
email,
});
};
export const sendSubscriptionCheckDialogShown = ({
mode,
id,
}: {|
mode: string,
id: string,
|}) => {
recordEvent('subscription-check-dialog-shown', {
mode, | No issues found. |
export const sendUserSurveyStarted = () => {
recordEvent('user_survey_started');
};
export const sendUserSurveyCompleted = () => {
recordEvent('user_survey_completed');
};
export const sendUserSurveyHidden = () => {
recordEvent('user_survey_hidden');
};
export const sendHelpSearch = (searchText: string) => {
recordEvent('help_search', {
searchText,
});
};
export const sendErrorMessage = (
message: string,
type:
| 'error'
| 'error-boundary_mainframe'
| 'error-boundary_list-search-result'
| 'error-boundary_box-search-result'
| 'error-boundary_app',
rawError: any,
errorId: string
) => {
recordEvent('error_message', {
message,
type,
rawError,
errorId,
});
};
export const sendSignupDone = (email: string) => {
recordEvent('signup', {
email,
});
};
export const sendSubscriptionCheckDialogShown = ({
mode,
id,
}: {|
mode: string,
id: string,
|}) => {
recordEvent('subscription-check-dialog-shown', {
mode, | @@ -621,3 +621,32 @@ export const sendInAppTutorialProgress = ({
nextCheckTimeoutId: setTimeout(() => immediatelyRecordEvent(true), 30000),
};
};
+
+export const sendAssetSwapStart = ({
+ originalObjectName,
+ objectType,
+}: {|
+ originalObjectName: string,
+ objectType: string,
+|}) => {
+ recordEvent('asset_swap_start', {
+ originalObjectName,
+ objectType,
+ });
+};
+
+export const sendAssetSwapFinished = ({
+ originalObjectName,
+ newObjectName,
+ objectType,
+}: {|
+ originalObjectName: string,
+ newObjectName: string,
+ objectType: string,
+|}) => {
+ recordEvent('asset_swap_finished', {
+ originalObjectName,
+ newObjectName,
+ objectType,
+ });
+}; | newIDE/app/src/Utils/Analytics/EventSender.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Add events when swapping assets | 7,450 | 4ian/GDevelop | 10,154 | JavaScript | ClementPasteau | |
eventsBasedObject: gdEventsBasedObject
) => {
const { currentProject, editorTabs } = state;
if (!currentProject) return;
const foundTab = getCustomObjectEditor(
editorTabs,
eventsFunctionsExtension,
eventsBasedObject
);
if (foundTab) {
setState(state => ({
...state,
editorTabs: changeCurrentTab(editorTabs, foundTab.tabIndex),
}));
} else {
// Open a new editor for the extension and the given function
setState(state => ({
...state,
editorTabs: openEditorTab(state.editorTabs, {
...getEditorOpeningOptions({
kind: 'custom object',
name:
eventsFunctionsExtension.getName() +
'::' +
eventsBasedObject.getName(),
project: currentProject,
}),
}),
}));
}
},
[getEditorOpeningOptions, setState, state]
);
const openObjectEvents = (extensionName: string, objectName: string) => {
const { currentProject, editorTabs } = state;
if (!currentProject) return;
if (currentProject.hasEventsFunctionsExtensionNamed(extensionName)) {
// It's an events functions extension, open the editor for it.
const eventsFunctionsExtension = currentProject.getEventsFunctionsExtension(
extensionName
);
const foundTab = getEventsFunctionsExtensionEditor(
editorTabs,
eventsFunctionsExtension
);
if (foundTab) {
// Open the given function and focus the tab | No issues found. | eventsBasedObject: gdEventsBasedObject
) => {
const { currentProject, editorTabs } = state;
if (!currentProject) return;
const foundTab = getCustomObjectEditor(
editorTabs,
eventsFunctionsExtension,
eventsBasedObject
);
if (foundTab) {
setState(state => ({
...state,
editorTabs: changeCurrentTab(editorTabs, foundTab.tabIndex),
}));
} else {
// Open a new editor for the extension and the given function
setState(state => ({
...state,
editorTabs: openEditorTab(state.editorTabs, {
...getEditorOpeningOptions({
kind: 'custom object',
name:
eventsFunctionsExtension.getName() +
'::' +
eventsBasedObject.getName(),
project: currentProject,
}),
}),
}));
}
},
[getEditorOpeningOptions, setState, state]
);
const openObjectEvents = (extensionName: string, objectName: string) => {
const { currentProject, editorTabs } = state;
if (!currentProject) return;
if (currentProject.hasEventsFunctionsExtensionNamed(extensionName)) {
// It's an events functions extension, open the editor for it.
const eventsFunctionsExtension = currentProject.getEventsFunctionsExtension(
extensionName
);
const foundTab = getEventsFunctionsExtensionEditor(
editorTabs,
eventsFunctionsExtension
);
if (foundTab) {
// Open the given function and focus the tab | @@ -489,8 +489,6 @@ const MainFrame = (props: Props) => {
setQuickCustomizationDialogOpenedFromGameId,
] = React.useState<?string>(null);
- const { getAuthenticatedPlayerForPreview } = useAuthenticatedPlayer();
-
// This is just for testing, to check if we're getting the right state
// and gives us an idea about the number of re-renders.
// React.useEffect(() => {
@@ -546,6 +544,11 @@ const MainFrame = (props: Props) => {
getHotReloadPreviewLaunchCaptureOptions,
} = useCapturesManager({ project: currentProject, gamesList });
+ const { getAuthenticatedPlayerForPreview } = useAuthenticatedPlayer({
+ project: currentProject,
+ gamesList,
+ });
+
/**
* This reference is useful to get the current opened project,
* even in the callback of a hook/promise - without risking to read "stale" data.
@@ -1674,9 +1677,7 @@ const MainFrame = (props: Props) => {
}
: null;
- const authenticatedPlayer = await getAuthenticatedPlayerForPreview(
- currentProject
- );
+ const authenticatedPlayer = await getAuthenticatedPlayerForPreview();
const captureOptions = await createCaptureOptionsForPreview(
launchCaptureOptions | newIDE/app/src/MainFrame/index.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Update player token logic to be fetched on project opening | 7,460 | 4ian/GDevelop | 10,154 | JavaScript | ClementPasteau | |
// Already unloaded.
return;
}
if (timeoutToUnloadIframe.current) {
// Cancel the previous timeout to start a new one.
clearTimeout(timeoutToUnloadIframe.current);
timeoutToUnloadIframe.current = null;
}
// The iframe becomes invisible right away,
// but we wait a bit before unloading it, so that navigating to another
// page doesn't cause the iframe to be reloaded.
setIframeVisible(false);
timeoutToUnloadIframe.current = setTimeout(() => {
setLoadIframeInDOM(false);
setIframeLoaded(false);
}, TIMEOUT_TO_UNLOAD_IFRAME_IN_MS);
},
[iframeLoaded, loadIframeInDOM]
);
const loadIframeOrRemoveTimeout = React.useCallback(() => {
if (timeoutToUnloadIframe.current) {
clearTimeout(timeoutToUnloadIframe.current);
timeoutToUnloadIframe.current = null;
}
ensureGDevelopGamesMonetizationReady();
// The iframe is loaded on the same page as where it's displayed,
// so we assume it's visible right away.
setLoadIframeInDOM(true);
setIframeVisible(true);
setIframeErrored(false);
}, []);
const notifyIframeToChangeGame = React.useCallback(
(gameId: string) => {
if (iframeLoaded) {
// $FlowFixMe - we know it's an iframe.
const iframe: ?HTMLIFrameElement = document.getElementById(
GAMES_PLATFORM_IFRAME_ID
);
if (iframe && iframe.contentWindow) {
iframe.contentWindow.postMessage(
{
id: 'openGame',
gameId,
},
'*'
); | No issues found. | // Already unloaded.
return;
}
if (timeoutToUnloadIframe.current) {
// Cancel the previous timeout to start a new one.
clearTimeout(timeoutToUnloadIframe.current);
timeoutToUnloadIframe.current = null;
}
// The iframe becomes invisible right away,
// but we wait a bit before unloading it, so that navigating to another
// page doesn't cause the iframe to be reloaded.
setIframeVisible(false);
timeoutToUnloadIframe.current = setTimeout(() => {
setLoadIframeInDOM(false);
setIframeLoaded(false);
}, TIMEOUT_TO_UNLOAD_IFRAME_IN_MS);
},
[iframeLoaded, loadIframeInDOM]
);
const loadIframeOrRemoveTimeout = React.useCallback(() => {
if (timeoutToUnloadIframe.current) {
clearTimeout(timeoutToUnloadIframe.current);
timeoutToUnloadIframe.current = null;
}
ensureGDevelopGamesMonetizationReady();
// The iframe is loaded on the same page as where it's displayed,
// so we assume it's visible right away.
setLoadIframeInDOM(true);
setIframeVisible(true);
setIframeErrored(false);
}, []);
const notifyIframeToChangeGame = React.useCallback(
(gameId: string) => {
if (iframeLoaded) {
// $FlowFixMe - we know it's an iframe.
const iframe: ?HTMLIFrameElement = document.getElementById(
GAMES_PLATFORM_IFRAME_ID
);
if (iframe && iframe.contentWindow) {
iframe.contentWindow.postMessage(
{
id: 'openGame',
gameId,
},
'*'
); | @@ -13,6 +13,8 @@ import { isNativeMobileApp } from '../../../../Utils/Platform';
import Window from '../../../../Utils/Window';
import { delay } from '../../../../Utils/Delay';
import { useStableUpToDateRef } from '../../../../Utils/UseStableUpToDateCallback';
+import { useSoftKeyboardBottomOffset } from '../../../../UI/MobileSoftKeyboard';
+import { homepageMobileMenuHeight } from '../HomePageMenuBar';
const electron = optionalRequire('electron');
// If the iframe is displaying a game, it will continue playing its audio as long as the iframe
@@ -164,6 +166,29 @@ const useUserCustomToken = (): {|
return { userCustomToken };
};
+const sendSoftKeyboardOffsetToFrame = async (offset: number) => {
+ // $FlowFixMe - we know it's an iframe.
+ const iframe: ?HTMLIFrameElement = document.getElementById(
+ GAMES_PLATFORM_IFRAME_ID
+ );
+ if (!iframe || !iframe.contentWindow) {
+ return;
+ }
+
+ try {
+ iframe.contentWindow.postMessage(
+ {
+ type: 'setKeyboardOffset',
+ value: offset,
+ },
+ '*'
+ );
+ } catch (error) {
+ console.error('Error while sending keyboard offset to frame.', error);
+ return;
+ }
+};
+
type GamesPlatformFrameStateProviderProps = {|
children: React.Node,
|};
@@ -178,6 +203,9 @@ const GamesPlatformFrameStateProvider = ({
const [lastGameId, setLastGameId] = React.useState<?string>(null);
const timeoutToUnloadIframe = React.useRef<?TimeoutID>(null);
const { openUserPublicProfile } = React.useContext(PublicProfileContext);
+ const softKeyboardBottomOffset = useSoftKeyboardBottomOffset({
+ useCumulatedValue: false,
+ });
const {
onOpenLoginDialog,
onOpenCreateAccountDialog,
@@ -464,6 +492,18 @@ const GamesPlatformFrameStateProvider = ({
[sendUserCustomTokenToFrame]
);
+ React.useEffect(
+ () => {
+ if (!iframeLoaded) {
+ return;
+ }
+ const offset = softKeyboardBottomOffset - homepageMobileMenuHeight;
+ sendSoftKeybo | newIDE/app/src/MainFrame/EditorContainers/HomePage/PlaySection/GamesPlatformFrameContext.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Send message to gd.games iframe when keyboard opens | 7,472 | 4ian/GDevelop | 10,154 | JavaScript | AlexandreSi | |
const TabsTitlebarTooltip = ({ anchorElement, editorTab }: Props) => {
const gdevelopTheme = React.useContext(GDevelopThemeContext);
const [tooltipStyle, setTooltipStyle] = React.useState<Object>(
styles.tooltip
);
const brightness = gdevelopTheme.palette.type === 'dark' ? 0.978 : 0.224;
const editorTabMetadata = getEditorTabMetadata(editorTab);
React.useEffect(
() => {
const timeoutId = setTimeout(() => {
setTooltipStyle(currentStyle => ({
...currentStyle,
transition: 'transform 150ms ease-in-out',
}));
}, 100);
return () => clearTimeout(timeoutId);
},
// Apply transition after first display of tooltip to avoid having the
// transition weirdly applied from the 0;0 coordinates.
[]
);
const title = editorKindToLabel[editorTabMetadata.editorKind];
let subtitle = null;
if (
[
'layout',
'layout events',
'external layout',
'external events',
'events functions extension',
].includes(editorTabMetadata.editorKind)
) {
subtitle = editorTabMetadata.projectItemName;
} else if (
editorTabMetadata.editorKind === 'custom object' &&
editorTabMetadata.projectItemName
) {
const nameParts = editorTabMetadata.projectItemName.split('::');
const customObjectName = nameParts[1];
if (customObjectName) {
subtitle = customObjectName;
}
}
return (
<Popper
| No issues found. |
const TabsTitlebarTooltip = ({ anchorElement, editorTab }: Props) => {
const gdevelopTheme = React.useContext(GDevelopThemeContext);
const [tooltipStyle, setTooltipStyle] = React.useState<Object>(
styles.tooltip
);
const brightness = gdevelopTheme.palette.type === 'dark' ? 0.978 : 0.224;
const editorTabMetadata = getEditorTabMetadata(editorTab);
React.useEffect(
() => {
const timeoutId = setTimeout(() => {
setTooltipStyle(currentStyle => ({
...currentStyle,
transition: 'transform 150ms ease-in-out',
}));
}, 100);
return () => clearTimeout(timeoutId);
},
// Apply transition after first display of tooltip to avoid having the
// transition weirdly applied from the 0;0 coordinates.
[]
);
const title = editorKindToLabel[editorTabMetadata.editorKind];
let subtitle = null;
if (
[
'layout',
'layout events',
'external layout',
'external events',
'events functions extension',
].includes(editorTabMetadata.editorKind)
) {
subtitle = editorTabMetadata.projectItemName;
} else if (
editorTabMetadata.editorKind === 'custom object' &&
editorTabMetadata.projectItemName
) {
const nameParts = editorTabMetadata.projectItemName.split('::');
const customObjectName = nameParts[1];
if (customObjectName) {
subtitle = customObjectName;
}
}
return (
<Popper
| @@ -0,0 +1,162 @@
+// @flow
+import * as React from 'react';
+import { Trans } from '@lingui/macro';
+import Fade from '@material-ui/core/Fade';
+import Paper from '@material-ui/core/Paper';
+import Popper from '@material-ui/core/Popper';
+
+import GDevelopThemeContext from '../UI/Theme/GDevelopThemeContext';
+import {
+ getEditorTabMetadata,
+ type EditorTab,
+ type EditorKind,
+} from './EditorTabs/EditorTabsHandler';
+import { ColumnStackLayout } from '../UI/Layout';
+import { Line } from '../UI/Grid';
+import Text from '../UI/Text';
+
+const editorKindToLabel: { [kind: EditorKind]: React.Node } = {
+ layout: <Trans>Scene</Trans>,
+ 'layout events': <Trans>Scene events</Trans>,
+ 'external layout': <Trans>External layout</Trans>,
+ 'external events': <Trans>External events</Trans>,
+ 'events functions extension': <Trans>Extension</Trans>,
+ 'custom object': <Trans>Object</Trans>,
+ debugger: <Trans>Debugger</Trans>,
+ resources: <Trans>Resources</Trans>,
+ 'start page': <Trans>Homepage</Trans>,
+};
+
+const styles = {
+ paper: {
+ padding: '8px 10px',
+ minWidth: 180,
+ },
+ tabIcon: {
+ marginLeft: 4,
+ marginRight: 4,
+ display: 'flex',
+ },
+ emptyTabIcon: {
+ marginLeft: 4,
+ marginRight: 4,
+ height: 20,
+ width: 24,
+ display: 'flex',
+ },
+ tooltip: {
+ zIndex: 3,
+ maxWidth: 'min(90%, 300px)',
+ },
+};
+
+type Props = {|
+ anchorElement: HTMLElement,
+ editorTab: EditorTab,
+|};
+
+const TabsTitlebarTooltip = ({ anchorElement, editorTab }: Props) => {
+ const gdevelopTheme = React.useContext(GDevelopThemeContext);
+ const [tooltipStyle, setTooltipStyle] = React.useState<Object>(
+ styles.tooltip
+ );
+
+ const brightness = gdevelopTheme.palette.type === 'dark' ? 0.978 : 0.224;
+
+ const editorTabMetadata = getEditorTabMetadata(editorTab);
+
+ React.useEffect(
+ () => {
+ const timeoutId = setTimeout(() => {
+ | newIDE/app/src/MainFrame/TabsTitlebarTooltip.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Add tooltip for tabs | 7,482 | 4ian/GDevelop | 10,154 | JavaScript | AlexandreSi | |
_fetchUserGameTemplates = async () => {
const { authentication } = this.props;
const firebaseUser = this.state.authenticatedUser.firebaseUser;
if (!firebaseUser) return;
try {
const receivedGameTemplates = await listReceivedGameTemplates(
authentication.getAuthorizationHeader,
{
userId: firebaseUser.uid,
}
);
this.setState(({ authenticatedUser }) => ({
authenticatedUser: {
...authenticatedUser,
receivedGameTemplates,
},
}));
} catch (error) {
console.error('Error while loading received game templates:', error);
}
};
_fetchUserGameTemplatePurchases = async () => {
const { authentication } = this.props;
const firebaseUser = this.state.authenticatedUser.firebaseUser;
if (!firebaseUser) return;
try {
const gameTemplatePurchases = await listUserPurchases(
authentication.getAuthorizationHeader,
{
userId: firebaseUser.uid,
productType: 'game-template',
role: 'receiver',
}
);
this.setState(({ authenticatedUser }) => ({
authenticatedUser: {
...authenticatedUser,
gameTemplatePurchases,
},
}));
} catch (error) {
console.error('Error while loading game template purchases:', error);
}
};
| No issues found. |
_fetchUserGameTemplates = async () => {
const { authentication } = this.props;
const firebaseUser = this.state.authenticatedUser.firebaseUser;
if (!firebaseUser) return;
try {
const receivedGameTemplates = await listReceivedGameTemplates(
authentication.getAuthorizationHeader,
{
userId: firebaseUser.uid,
}
);
this.setState(({ authenticatedUser }) => ({
authenticatedUser: {
...authenticatedUser,
receivedGameTemplates,
},
}));
} catch (error) {
console.error('Error while loading received game templates:', error);
}
};
_fetchUserGameTemplatePurchases = async () => {
const { authentication } = this.props;
const firebaseUser = this.state.authenticatedUser.firebaseUser;
if (!firebaseUser) return;
try {
const gameTemplatePurchases = await listUserPurchases(
authentication.getAuthorizationHeader,
{
userId: firebaseUser.uid,
productType: 'game-template',
role: 'receiver',
}
);
this.setState(({ authenticatedUser }) => ({
authenticatedUser: {
...authenticatedUser,
gameTemplatePurchases,
},
}));
} catch (error) {
console.error('Error while loading game template purchases:', error);
}
};
| @@ -41,9 +41,7 @@ import CreateAccountDialog from './CreateAccountDialog';
import EditProfileDialog from './EditProfileDialog';
import ChangeEmailDialog from './ChangeEmailDialog';
import EmailVerificationDialog from './EmailVerificationDialog';
-import PreferencesContext, {
- type PreferencesValues,
-} from '../MainFrame/Preferences/PreferencesContext';
+import { type PreferencesValues } from '../MainFrame/Preferences/PreferencesContext';
import {
listUserCloudProjects,
type CloudProjectWithUserAccessInfo,
@@ -63,16 +61,15 @@ import { showErrorBox } from '../UI/Messages/MessageBox';
import { userCancellationErrorName } from '../LoginProvider/Utils';
import { listUserPurchases } from '../Utils/GDevelopServices/Shop';
import { listNotifications } from '../Utils/GDevelopServices/Notification';
-import ProfileDialog from './ProfileDialog';
type Props = {|
authentication: Authentication,
+ preferencesValues: PreferencesValues,
children: React.Node,
|};
type State = {|
authenticatedUser: AuthenticatedUser,
- profileDialogOpen: boolean,
loginDialogOpen: boolean,
createAccountDialogOpen: boolean,
loginInProgress: boolean,
@@ -109,7 +106,6 @@ export default class AuthenticatedUserProvider extends React.Component<
> {
state = {
authenticatedUser: initialAuthenticatedUser,
- profileDialogOpen: false,
loginDialogOpen: false,
createAccountDialogOpen: false,
loginInProgress: false,
@@ -215,7 +211,6 @@ export default class AuthenticatedUserProvider extends React.Component<
onOpenEditProfileDialog: () => this.openEditProfileDialog(true),
onOpenChangeEmailDialog: () => this.openChangeEmailDialog(true),
onOpenCreateAccountDialog: () => this.openCreateAccountDialog(true),
- onOpenProfileDialog: () => this.openProfileDialog(true),
onRefreshUserProfile: this._fetchUserProfile,
onRefreshFirebaseProfile: async () => {
await this._reloadFirebaseProfile();
@@ - | newIDE/app/src/Profile/AuthenticatedUserProvider.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Fix "Manage subscription" button not working | 7,507 | 4ian/GDevelop | 10,154 | JavaScript | ClementPasteau | |
type Props = {|
anchorElement: HTMLElement,
editorTab: EditorTab,
|};
const TabsTitlebarTooltip = ({ anchorElement, editorTab }: Props) => {
const gdevelopTheme = React.useContext(GDevelopThemeContext);
const [tooltipStyle, setTooltipStyle] = React.useState<Object>(
styles.tooltip
);
const editorTabMetadata = getEditorTabMetadata(editorTab);
React.useEffect(
() => {
const timeoutId = setTimeout(() => {
setTooltipStyle(currentStyle => ({
...currentStyle,
transition: 'transform 150ms ease-in-out',
}));
}, 100);
return () => clearTimeout(timeoutId);
},
// Apply transition after first display of tooltip to avoid having the
// transition weirdly applied from the 0;0 coordinates.
[]
);
let title = null;
let subtitle = null;
if (
[
'layout',
'layout events',
'external layout',
'external events',
'events functions extension',
].includes(editorTabMetadata.editorKind)
) {
title = editorTabMetadata.projectItemName;
subtitle = editorKindToLabel[editorTabMetadata.editorKind];
} else if (
editorTabMetadata.editorKind === 'custom object' &&
editorTabMetadata.projectItemName
) {
const nameParts = editorTabMetadata.projectItemName.split('::');
const customObjectName = nameParts[1];
if (customObjectName) {
title = customObjectName;
subtitle = editorKindToLabel[editorTabMetadata.editorKind];
}
| No issues found. | type Props = {|
anchorElement: HTMLElement,
editorTab: EditorTab,
|};
const TabsTitlebarTooltip = ({ anchorElement, editorTab }: Props) => {
const gdevelopTheme = React.useContext(GDevelopThemeContext);
const [tooltipStyle, setTooltipStyle] = React.useState<Object>(
styles.tooltip
);
const editorTabMetadata = getEditorTabMetadata(editorTab);
React.useEffect(
() => {
const timeoutId = setTimeout(() => {
setTooltipStyle(currentStyle => ({
...currentStyle,
transition: 'transform 150ms ease-in-out',
}));
}, 100);
return () => clearTimeout(timeoutId);
},
// Apply transition after first display of tooltip to avoid having the
// transition weirdly applied from the 0;0 coordinates.
[]
);
let title = null;
let subtitle = null;
if (
[
'layout',
'layout events',
'external layout',
'external events',
'events functions extension',
].includes(editorTabMetadata.editorKind)
) {
title = editorTabMetadata.projectItemName;
subtitle = editorKindToLabel[editorTabMetadata.editorKind];
} else if (
editorTabMetadata.editorKind === 'custom object' &&
editorTabMetadata.projectItemName
) {
const nameParts = editorTabMetadata.projectItemName.split('::');
const customObjectName = nameParts[1];
if (customObjectName) {
title = customObjectName;
subtitle = editorKindToLabel[editorTabMetadata.editorKind];
}
| @@ -12,7 +12,6 @@ import {
type EditorKind,
} from './EditorTabs/EditorTabsHandler';
import { ColumnStackLayout } from '../UI/Layout';
-import { Line } from '../UI/Grid';
import Text from '../UI/Text';
const editorKindToLabel: { [kind: EditorKind]: React.Node } = {
@@ -25,6 +24,7 @@ const editorKindToLabel: { [kind: EditorKind]: React.Node } = {
debugger: <Trans>Debugger</Trans>,
resources: <Trans>Resources</Trans>,
'start page': <Trans>Homepage</Trans>,
+ 'ask-ai': <Trans>Ask AI</Trans>,
};
const styles = {
@@ -61,8 +61,6 @@ const TabsTitlebarTooltip = ({ anchorElement, editorTab }: Props) => {
styles.tooltip
);
- const brightness = gdevelopTheme.palette.type === 'dark' ? 0.978 : 0.224;
-
const editorTabMetadata = getEditorTabMetadata(editorTab);
React.useEffect(
@@ -80,7 +78,7 @@ const TabsTitlebarTooltip = ({ anchorElement, editorTab }: Props) => {
[]
);
- const title = editorKindToLabel[editorTabMetadata.editorKind];
+ let title = null;
let subtitle = null;
if (
[
@@ -91,16 +89,20 @@ const TabsTitlebarTooltip = ({ anchorElement, editorTab }: Props) => {
'events functions extension',
].includes(editorTabMetadata.editorKind)
) {
- subtitle = editorTabMetadata.projectItemName;
+ title = editorTabMetadata.projectItemName;
+ subtitle = editorKindToLabel[editorTabMetadata.editorKind];
} else if (
editorTabMetadata.editorKind === 'custom object' &&
editorTabMetadata.projectItemName
) {
const nameParts = editorTabMetadata.projectItemName.split('::');
const customObjectName = nameParts[1];
if (customObjectName) {
- subtitle = customObjectName;
+ title = customObjectName;
+ subtitle = editorKindToLabel[editorTabMetadata.editorKind];
}
+ } else {
+ title = editorKindToLabel[editorTabMetadata.editorKind];
}
return (
@@ -135,21 +137,11 @@ const TabsTitlebarTooltip = ({ ancho | newIDE/app/src/MainFrame/TabsTitlebarTooltip.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Fix tab tooltip being stuck when closing tab + improve design | 7,513 | 4ian/GDevelop | 10,154 | JavaScript | ClementPasteau | |
onResourcePathUpdated();
forceUpdate();
await resourceManagementProps.onFetchNewlyAddedResources();
},
[resourceManagementProps, resources, onResourcePathUpdated, forceUpdate]
);
const resourceSources = React.useMemo(
() => {
const storageProvider = resourceManagementProps.getStorageProvider();
return resources.length
? resourceManagementProps.resourceSources
.filter(source => source.kind === resources[0].getKind())
.filter(
({ onlyForStorageProvider }) =>
!onlyForStorageProvider ||
onlyForStorageProvider === storageProvider.internalName
)
.filter(source => !source.hideInResourceEditor)
: [];
},
[resourceManagementProps, resources]
);
const schema: Schema = React.useMemo(
() => [
{
name: 'Resource name',
valueType: 'string',
disabled: () => true,
getValue: (resource: gdResource) => resource.getName(),
setValue: (resource: gdResource, newValue: string) =>
resource.setName(newValue),
},
{
name: 'File',
valueType: 'string',
getValue: (resource: gdResource) => resource.getFile(),
setValue: (resource: gdResource, newValue: string) =>
resource.setFile(newValue),
onEditButtonClick: () => {
const firstResourceSource = resourceSources[0];
if (firstResourceSource) chooseResourcePath(firstResourceSource);
},
onEditButtonBuildMenuTemplate:
resourceSources.length > 1
? (i18n: I18nType) =>
resourceSources.map(source => ({
label: i18n._(source.displayName), | No issues found. |
onResourcePathUpdated();
forceUpdate();
await resourceManagementProps.onFetchNewlyAddedResources();
},
[resourceManagementProps, resources, onResourcePathUpdated, forceUpdate]
);
const resourceSources = React.useMemo(
() => {
const storageProvider = resourceManagementProps.getStorageProvider();
return resources.length
? resourceManagementProps.resourceSources
.filter(source => source.kind === resources[0].getKind())
.filter(
({ onlyForStorageProvider }) =>
!onlyForStorageProvider ||
onlyForStorageProvider === storageProvider.internalName
)
.filter(source => !source.hideInResourceEditor)
: [];
},
[resourceManagementProps, resources]
);
const schema: Schema = React.useMemo(
() => [
{
name: 'Resource name',
valueType: 'string',
disabled: () => true,
getValue: (resource: gdResource) => resource.getName(),
setValue: (resource: gdResource, newValue: string) =>
resource.setName(newValue),
},
{
name: 'File',
valueType: 'string',
getValue: (resource: gdResource) => resource.getFile(),
setValue: (resource: gdResource, newValue: string) =>
resource.setFile(newValue),
onEditButtonClick: () => {
const firstResourceSource = resourceSources[0];
if (firstResourceSource) chooseResourcePath(firstResourceSource);
},
onEditButtonBuildMenuTemplate:
resourceSources.length > 1
? (i18n: I18nType) =>
resourceSources.map(source => ({
label: i18n._(source.displayName), | @@ -85,6 +85,23 @@ const ResourcePropertiesEditor = React.forwardRef<
[resourceManagementProps, resources, onResourcePathUpdated, forceUpdate]
);
+ const resourceSources = React.useMemo(
+ () => {
+ const storageProvider = resourceManagementProps.getStorageProvider();
+ return resources.length
+ ? resourceManagementProps.resourceSources
+ .filter(source => source.kind === resources[0].getKind())
+ .filter(
+ ({ onlyForStorageProvider }) =>
+ !onlyForStorageProvider ||
+ onlyForStorageProvider === storageProvider.internalName
+ )
+ .filter(source => !source.hideInResourceEditor)
+ : [];
+ },
+ [resourceManagementProps, resources]
+ );
+
const schema: Schema = React.useMemo(
() => [
{
@@ -102,35 +119,20 @@ const ResourcePropertiesEditor = React.forwardRef<
setValue: (resource: gdResource, newValue: string) =>
resource.setFile(newValue),
onEditButtonClick: () => {
- const storageProvider = resourceManagementProps.getStorageProvider();
- const resourceSources = resourceManagementProps.resourceSources
- .filter(source => source.kind === resources[0].getKind())
- .filter(
- ({ onlyForStorageProvider }) =>
- !onlyForStorageProvider ||
- onlyForStorageProvider === storageProvider.internalName
- );
-
const firstResourceSource = resourceSources[0];
if (firstResourceSource) chooseResourcePath(firstResourceSource);
},
- onEditButtonBuildMenuTemplate: (i18n: I18nType) => {
- const storageProvider = resourceManagementProps.getStorageProvider();
- return resourceManagementProps.resourceSources
- .filter(source => source.kind === resources[0].getKind())
- .filte | newIDE/app/src/ResourcesEditor/ResourcePropertiesEditor/index.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Update worker url logic + consistent lights + fix using in resources list | 7,551 | 4ian/GDevelop | 10,154 | JavaScript | ClementPasteau | |
return buildLastWeekChartData(lastWeekGameMetrics);
},
[gameMetrics, oneWeekAgoIsoDate]
);
return (
<>
<I18n>
{({ i18n }) => (
<DashboardWidget
widgetSize={'twoThirds'}
minHeight
title={<Trans>Analytics</Trans>}
topRightAction={
<FlatButton
label={<Trans>See all</Trans>}
rightIcon={<ArrowRight fontSize="small" />}
onClick={onSeeAll}
primary
/>
}
widgetName="analytics"
>
<ResponsiveLineStackLayout expand noColumnMargin noMargin>
{!gameMetrics ? (
<div style={styles.loadingSpace} />
) : hasNoSession ? (
gameUrl ? (
<ColumnStackLayout
noMargin
alignItems={isMobile ? 'stretch' : 'flex-start'}
noOverflowParent
>
<Spacer />
<Text noMargin color="secondary">
<Trans>
No data to show yet. Share your game creator profile
with more people to get more players!
</Trans>
</Text>
<GameLinkAndShareIcons display="column" url={gameUrl} />
</ColumnStackLayout>
) : (
<ColumnStackLayout
noMargin
expand
justifyContent="center"
alignItems="center"
>
<Spacer />
<Text color="secondary" noMargin> | No issues found. | return buildLastWeekChartData(lastWeekGameMetrics);
},
[gameMetrics, oneWeekAgoIsoDate]
);
return (
<>
<I18n>
{({ i18n }) => (
<DashboardWidget
widgetSize={'twoThirds'}
minHeight
title={<Trans>Analytics</Trans>}
topRightAction={
<FlatButton
label={<Trans>See all</Trans>}
rightIcon={<ArrowRight fontSize="small" />}
onClick={onSeeAll}
primary
/>
}
widgetName="analytics"
>
<ResponsiveLineStackLayout expand noColumnMargin noMargin>
{!gameMetrics ? (
<div style={styles.loadingSpace} />
) : hasNoSession ? (
gameUrl ? (
<ColumnStackLayout
noMargin
alignItems={isMobile ? 'stretch' : 'flex-start'}
noOverflowParent
>
<Spacer />
<Text noMargin color="secondary">
<Trans>
No data to show yet. Share your game creator profile
with more people to get more players!
</Trans>
</Text>
<GameLinkAndShareIcons display="column" url={gameUrl} />
</ColumnStackLayout>
) : (
<ColumnStackLayout
noMargin
expand
justifyContent="center"
alignItems="center"
>
<Spacer />
<Text color="secondary" noMargin> | @@ -119,7 +119,7 @@ const AnalyticsWidget = ({ game, onSeeAll, gameMetrics, gameUrl }: Props) => {
) : (
<Column expand noMargin>
<Line alignItems="center" justifyContent="space-between">
- <Text size="block-title" noMargin>
+ <Text size="sub-title" noMargin>
<Trans>Sessions</Trans>
</Text>
<RaisedButton | newIDE/app/src/GameDashboard/Widgets/AnalyticsWidget.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Add tooltip in game analytics | 7,559 | 4ian/GDevelop | 10,154 | JavaScript | Bouh | |
(effect: gdEffect) => {
effectsContainer.removeEffect(effect.getName());
onUpdate();
onEffectsUpdated();
},
[effectsContainer, onUpdate, onEffectsUpdated]
);
const copyEffect = React.useCallback(
(effect: gdEffect) => {
Clipboard.set(EFFECTS_CLIPBOARD_KIND, [
{
name: effect.getName(),
type: effect.getEffectType(),
serializedEffect: serializeToJSObject(effect),
},
]);
onUpdate();
},
[onUpdate]
);
const copyAllEffects = React.useCallback(
() => {
Clipboard.set(
EFFECTS_CLIPBOARD_KIND,
mapFor(0, effectsContainer.getEffectsCount(), (index: number) => {
const effect: gdEffect = effectsContainer.getEffectAt(index);
return {
name: effect.getName(),
type: effect.getEffectType(),
serializedEffect: serializeToJSObject(effect),
};
})
);
onUpdate();
},
[onUpdate, effectsContainer]
);
const pasteEffects = React.useCallback(
async effectInsertionIndex => {
const clipboardContent = Clipboard.get(EFFECTS_CLIPBOARD_KIND);
const effectContents = SafeExtractor.extractArray(clipboardContent);
if (!effectContents) return;
const newNamedEffects: Array<{
name: string,
serializedEffect: string,
}> = [];
const existingNamedEffects: Array<{ | No issues found. | (effect: gdEffect) => {
effectsContainer.removeEffect(effect.getName());
onUpdate();
onEffectsUpdated();
},
[effectsContainer, onUpdate, onEffectsUpdated]
);
const copyEffect = React.useCallback(
(effect: gdEffect) => {
Clipboard.set(EFFECTS_CLIPBOARD_KIND, [
{
name: effect.getName(),
type: effect.getEffectType(),
serializedEffect: serializeToJSObject(effect),
},
]);
onUpdate();
},
[onUpdate]
);
const copyAllEffects = React.useCallback(
() => {
Clipboard.set(
EFFECTS_CLIPBOARD_KIND,
mapFor(0, effectsContainer.getEffectsCount(), (index: number) => {
const effect: gdEffect = effectsContainer.getEffectAt(index);
return {
name: effect.getName(),
type: effect.getEffectType(),
serializedEffect: serializeToJSObject(effect),
};
})
);
onUpdate();
},
[onUpdate, effectsContainer]
);
const pasteEffects = React.useCallback(
async effectInsertionIndex => {
const clipboardContent = Clipboard.get(EFFECTS_CLIPBOARD_KIND);
const effectContents = SafeExtractor.extractArray(clipboardContent);
if (!effectContents) return;
const newNamedEffects: Array<{
name: string,
serializedEffect: string,
}> = [];
const existingNamedEffects: Array<{ | @@ -53,6 +53,8 @@ import PasteIcon from '../UI/CustomSvgIcons/Clipboard';
import CopyIcon from '../UI/CustomSvgIcons/Copy';
import { type ConnectDragSource } from 'react-dnd';
import ResponsiveFlatButton from '../UI/ResponsiveFlatButton';
+import { Accordion, AccordionHeader, AccordionBody } from '../UI/Accordion';
+import { type Field } from '../CompactPropertiesEditor';
const gd: libGDevelop = global.gd;
@@ -132,14 +134,12 @@ const Effect = React.forwardRef(
ref
) => {
const gdevelopTheme = React.useContext(GDevelopThemeContext);
-
const preferences = React.useContext(PreferencesContext);
const showEffectParameterNames =
preferences.values.showEffectParameterNames;
const setShowEffectParameterNames = preferences.setShowEffectParameterNames;
const forceUpdate = useForceUpdate();
-
const isClipboardContainingEffects = Clipboard.has(EFFECTS_CLIPBOARD_KIND);
const renameEffect = React.useCallback(
@@ -190,6 +190,42 @@ const Effect = React.forwardRef(
effectType
);
+ const parametersSchema = effectMetadata && effectMetadata.parametersSchema;
+ const basicPropertiesSchema = React.useMemo(
+ () =>
+ parametersSchema
+ ? parametersSchema.filter(param => param.valueType && !param.advanced)
+ : [],
+ [parametersSchema]
+ );
+ const advancedPropertiesSchema = React.useMemo(
+ () =>
+ parametersSchema
+ ? parametersSchema.filter(param => param.valueType && param.advanced)
+ : [],
+ [parametersSchema]
+ );
+
+ const areAdvancedPropertiesModified = React.useMemo(
+ () => {
+ return advancedPropertiesSchema.some((field: Field) => {
+ const name = field.valueType ? field.name : null;
+ if (!name) return false;
+
+ const current =
+ field.valueType === 'number'
+ ? effect.getDoubleParameter(name)
+ : field.valueType === 'boolean'
+ | newIDE/app/src/EffectsList/index.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | [DRAFT] implementation of Shadowmapping | 7,592 | 4ian/GDevelop | 10,154 | JavaScript | NeylMahfouf2608 | |
} else if (input === 'Release Ladder') {
this._releaseLadderKey = true;
}
}
/**.
* @param input The control to be tested [Left,Right,Up,Down,Ladder,Jump,Release,Release Ladder].
* @returns true if the key was used since the last `doStepPreEvents` call.
*/
isUsingControl(input: string): boolean {
if (input === 'Left') {
return this._wasLeftKeyPressed;
}
if (input === 'Right') {
return this._wasRightKeyPressed;
}
if (input === 'Up') {
return this._wasUpKeyPressed;
}
if (input === 'Down') {
return this._wasDownKeyPressed;
}
if (input === 'Ladder') {
return this._wasLadderKeyPressed;
}
if (input === 'Jump') {
return this._wasJumpKeyPressed;
}
if (input === 'Release') {
return this._wasReleasePlatformKeyPressed;
}
if (input === 'Release Ladder') {
return this._wasReleaseLadderKeyPressed;
}
return false;
}
/**
* Get the gravity of the Platformer Object.
* @returns The current gravity.
*/
getGravity(): float {
return this._gravity;
}
/**
* Get maximum angle of a slope for the Platformer Object to run on it as a floor.
* @returns the slope maximum angle, in degrees.
*/
getSlopeMaxAngle(): float {
return this._slopeMaxAngle; | No issues found. | } else if (input === 'Release Ladder') {
this._releaseLadderKey = true;
}
}
/**.
* @param input The control to be tested [Left,Right,Up,Down,Ladder,Jump,Release,Release Ladder].
* @returns true if the key was used since the last `doStepPreEvents` call.
*/
isUsingControl(input: string): boolean {
if (input === 'Left') {
return this._wasLeftKeyPressed;
}
if (input === 'Right') {
return this._wasRightKeyPressed;
}
if (input === 'Up') {
return this._wasUpKeyPressed;
}
if (input === 'Down') {
return this._wasDownKeyPressed;
}
if (input === 'Ladder') {
return this._wasLadderKeyPressed;
}
if (input === 'Jump') {
return this._wasJumpKeyPressed;
}
if (input === 'Release') {
return this._wasReleasePlatformKeyPressed;
}
if (input === 'Release Ladder') {
return this._wasReleaseLadderKeyPressed;
}
return false;
}
/**
* Get the gravity of the Platformer Object.
* @returns The current gravity.
*/
getGravity(): float {
return this._gravity;
}
/**
* Get maximum angle of a slope for the Platformer Object to run on it as a floor.
* @returns the slope maximum angle, in degrees.
*/
getSlopeMaxAngle(): float {
return this._slopeMaxAngle; | @@ -23,7 +23,6 @@ namespace gdjs {
interface JumpingStateNetworkSyncData {
cjs: number;
tscjs: number;
- jkhsjs: boolean;
jfd: boolean;
}
@@ -57,6 +56,7 @@ namespace gdjs {
juk: boolean;
rpk: boolean;
rlk: boolean;
+ jkhsjs: boolean;
sn: string;
ssd: StateNetworkSyncData;
}
@@ -119,6 +119,7 @@ namespace gdjs {
private _xGrabTolerance: any;
_useLegacyTrajectory: boolean;
+ _useRepeatedJump: boolean;
_canGoDownFromJumpthru: boolean = false;
@@ -139,6 +140,7 @@ namespace gdjs {
_upKey: boolean = false;
_downKey: boolean = false;
_jumpKey: boolean = false;
+ _jumpKeyHeldSinceJumpStart: boolean = false;
_releasePlatformKey: boolean = false;
_releaseLadderKey: boolean = false;
@@ -204,6 +206,10 @@ namespace gdjs {
behaviorData.useLegacyTrajectory === undefined
? true
: behaviorData.useLegacyTrajectory;
+ this._useRepeatedJump =
+ behaviorData.useRepeatedJump === undefined
+ ? true
+ : behaviorData.useRepeatedJump;
this._canGoDownFromJumpthru = behaviorData.canGoDownFromJumpthru;
this._slopeMaxAngle = 0;
this.setSlopeMaxAngle(behaviorData.slopeMaxAngle);
@@ -249,6 +255,7 @@ namespace gdjs {
juk: this._wasJumpKeyPressed,
rpk: this._wasReleasePlatformKeyPressed,
rlk: this._wasReleaseLadderKeyPressed,
+ jkhsjs: this._jumpKeyHeldSinceJumpStart,
sn: this._state.toString(),
ssd: this._state.getNetworkSyncData(),
},
@@ -306,6 +313,9 @@ namespace gdjs {
if (behaviorSpecificProps.rlk !== this._releaseLadderKey) {
this._releaseLadderKey = behaviorSpecificProps.rlk;
}
+ if (behaviorSpecificProps.jkhsjs !== this._jumpKeyHeldSinceJumpStart) {
+ this._jumpKeyHeldSinceJumpStart = behaviorSpecificProps.jkhsjs;
+ }
if (behaviorSpecificProps.sn !== this._state.toString()) {
| Extensions/PlatformBehavior/platformerobjectruntimebehavior.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | [Platformer] Forbid repeated jumps while holding the jump key | 7,648 | 4ian/GDevelop | 10,154 | JavaScript | D8H | |
threeObject3D.position.set(
this._object.isFlippedX() ? pivotX : -pivotX,
this._object.isFlippedY() ? pivotY : -pivotY,
this._object.isFlippedZ() ? pivotZ : -pivotZ
);
threeObject3D.position.applyEuler(threeObject3D.rotation);
threeObject3D.position.x += this._object.getX() + pivotX;
threeObject3D.position.y += this._object.getY() + pivotY;
threeObject3D.position.z += this._object.getZ() + pivotZ;
threeObject3D.scale.set(
this._object.isFlippedX() ? -scaleX : scaleX,
this._object.isFlippedY() ? -scaleY : scaleY,
this._object.isFlippedZ() ? -scaleZ : scaleZ
);
threeObject3D.visible = !this._object.hidden;
this._isContainerDirty = false;
}
/**
* Call this to make sure the object is ready to be rendered.
*/
ensureUpToDate() {
if (this._isContainerDirty) {
this._updateThreeGroup();
}
}
update(): void {
this._isContainerDirty = true;
}
updateX(): void {
this._isContainerDirty = true;
}
updateY(): void {
this._isContainerDirty = true;
}
updateAngle(): void {
this._isContainerDirty = true;
}
updatePosition() {
this._isContainerDirty = true;
}
| No issues found. |
threeObject3D.position.set(
this._object.isFlippedX() ? pivotX : -pivotX,
this._object.isFlippedY() ? pivotY : -pivotY,
this._object.isFlippedZ() ? pivotZ : -pivotZ
);
threeObject3D.position.applyEuler(threeObject3D.rotation);
threeObject3D.position.x += this._object.getX() + pivotX;
threeObject3D.position.y += this._object.getY() + pivotY;
threeObject3D.position.z += this._object.getZ() + pivotZ;
threeObject3D.scale.set(
this._object.isFlippedX() ? -scaleX : scaleX,
this._object.isFlippedY() ? -scaleY : scaleY,
this._object.isFlippedZ() ? -scaleZ : scaleZ
);
threeObject3D.visible = !this._object.hidden;
this._isContainerDirty = false;
}
/**
* Call this to make sure the object is ready to be rendered.
*/
ensureUpToDate() {
if (this._isContainerDirty) {
this._updateThreeGroup();
}
}
update(): void {
this._isContainerDirty = true;
}
updateX(): void {
this._isContainerDirty = true;
}
updateY(): void {
this._isContainerDirty = true;
}
updateAngle(): void {
this._isContainerDirty = true;
}
updatePosition() {
this._isContainerDirty = true;
}
| @@ -44,10 +44,7 @@ namespace gdjs {
) {
this._object = object;
this._isContainerDirty = true;
- const layer = parent.getLayer('');
- if (layer) {
- layer.getRenderer().add3DRendererObject(this._threeGroup);
- }
+ this._threeGroup.clear();
}
_updateThreeGroup() { | Extensions/3D/CustomRuntimeObject3DRenderer.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | Fix changing of variant not being applied at hot-reload | 7,666 | 4ian/GDevelop | 10,154 | JavaScript | D8H | |
.addIncludeFile('Extensions/Multiplayer/multiplayerVariablesManager.js')
.addIncludeFile('Extensions/Multiplayer/multiplayertools.js')
.setFunctionName(
'gdjs.multiplayerMessageManager.getLatestPlayerWhoJustLeft'
);
extension
.addCondition(
'HasAnyPlayerJoined',
_('Any player has joined'),
_('Check if any player has joined the lobby.'),
_('Any player has joined'),
_('Lobbies'),
'JsPlatform/Extensions/multiplayer.svg',
'JsPlatform/Extensions/multiplayer.svg'
)
.getCodeExtraInformation()
.setIncludeFile('Extensions/Multiplayer/peer.js')
.addIncludeFile('Extensions/Multiplayer/peerJsHelper.js')
.addIncludeFile(
'Extensions/PlayerAuthentication/playerauthenticationcomponents.js'
)
.addIncludeFile(
'Extensions/PlayerAuthentication/playerauthenticationtools.js'
)
.addIncludeFile('Extensions/Multiplayer/multiplayercomponents.js')
.addIncludeFile('Extensions/Multiplayer/messageManager.js')
.addIncludeFile('Extensions/Multiplayer/multiplayerVariablesManager.js')
.addIncludeFile('Extensions/Multiplayer/multiplayertools.js')
.setFunctionName('gdjs.multiplayerMessageManager.hasAnyPlayerJustJoined');
extension
.addCondition(
'HasPlayerJoined',
_('Player has joined'),
_('Check if the player has joined the lobby.'),
_('Player _PARAM0_ has joined'),
_('Lobbies'),
'JsPlatform/Extensions/multiplayer.svg',
'JsPlatform/Extensions/multiplayer.svg'
)
.getCodeExtraInformation()
.addParameter('number', _('Player number'), '', false)
.setIncludeFile('Extensions/Multiplayer/peer.js')
.addIncludeFile('Extensions/Multiplayer/peerJsHelper.js')
.addIncludeFile(
'Extensions/PlayerAuthentication/playerauthenticationcomponents.js'
)
.addIncludeFile(
'Extensions/PlayerAuthentication/playerauthenticationtools.js'
) | No issues found. | .addIncludeFile('Extensions/Multiplayer/multiplayerVariablesManager.js')
.addIncludeFile('Extensions/Multiplayer/multiplayertools.js')
.setFunctionName(
'gdjs.multiplayerMessageManager.getLatestPlayerWhoJustLeft'
);
extension
.addCondition(
'HasAnyPlayerJoined',
_('Any player has joined'),
_('Check if any player has joined the lobby.'),
_('Any player has joined'),
_('Lobbies'),
'JsPlatform/Extensions/multiplayer.svg',
'JsPlatform/Extensions/multiplayer.svg'
)
.getCodeExtraInformation()
.setIncludeFile('Extensions/Multiplayer/peer.js')
.addIncludeFile('Extensions/Multiplayer/peerJsHelper.js')
.addIncludeFile(
'Extensions/PlayerAuthentication/playerauthenticationcomponents.js'
)
.addIncludeFile(
'Extensions/PlayerAuthentication/playerauthenticationtools.js'
)
.addIncludeFile('Extensions/Multiplayer/multiplayercomponents.js')
.addIncludeFile('Extensions/Multiplayer/messageManager.js')
.addIncludeFile('Extensions/Multiplayer/multiplayerVariablesManager.js')
.addIncludeFile('Extensions/Multiplayer/multiplayertools.js')
.setFunctionName('gdjs.multiplayerMessageManager.hasAnyPlayerJustJoined');
extension
.addCondition(
'HasPlayerJoined',
_('Player has joined'),
_('Check if the player has joined the lobby.'),
_('Player _PARAM0_ has joined'),
_('Lobbies'),
'JsPlatform/Extensions/multiplayer.svg',
'JsPlatform/Extensions/multiplayer.svg'
)
.getCodeExtraInformation()
.addParameter('number', _('Player number'), '', false)
.setIncludeFile('Extensions/Multiplayer/peer.js')
.addIncludeFile('Extensions/Multiplayer/peerJsHelper.js')
.addIncludeFile(
'Extensions/PlayerAuthentication/playerauthenticationcomponents.js'
)
.addIncludeFile(
'Extensions/PlayerAuthentication/playerauthenticationtools.js'
) | @@ -31,6 +31,73 @@ module.exports = {
.addInstructionOrExpressionGroupMetadata(_('Multiplayer'))
.setIcon('JsPlatform/Extensions/multiplayer.svg');
+ extension
+ .addStrExpression(
+ 'CurrentLobbyID',
+ _('Current lobby ID'),
+ _('Returns current lobby ID.'),
+ _('Lobbies'),
+ 'JsPlatform/Extensions/multiplayer.svg'
+ )
+ .getCodeExtraInformation()
+ .setIncludeFile('Extensions/Multiplayer/peer.js')
+ .addIncludeFile('Extensions/Multiplayer/peerJsHelper.js')
+ .addIncludeFile(
+ 'Extensions/PlayerAuthentication/playerauthenticationcomponents.js'
+ )
+ .addIncludeFile(
+ 'Extensions/PlayerAuthentication/playerauthenticationtools.js'
+ )
+ .addIncludeFile('Extensions/Multiplayer/multiplayercomponents.js')
+ .addIncludeFile('Extensions/Multiplayer/messageManager.js')
+ .addIncludeFile('Extensions/Multiplayer/multiplayerVariablesManager.js')
+ .addIncludeFile('Extensions/Multiplayer/multiplayertools.js')
+ .setFunctionName('gdjs.multiplayer.getLobbyID');
+
+ extension
+ .addAction(
+ 'QuickJoinWithLobbyID',
+ _('Join a specific lobby by its ID'),
+ _(
+ 'Join a specific lobby. The player will join the game instantly if this is possible.'
+ ),
+ _('Join a specific lobby by its ID _PARAM1_'),
+ _('Lobbies'),
+ 'JsPlatform/Extensions/multiplayer.svg',
+ 'JsPlatform/Extensions/multiplayer.svg'
+ )
+ .addCodeOnlyParameter('currentScene', '')
+ .addParameter('string', _('Lobby ID'), '', false)
+ .addParameter(
+ 'yesorno',
+ _('Display loader while joining a lobby.'),
+ '',
+ true
+ )
+ .setDefaultValue('yes')
+ .addParameter(
+ 'yesorno',
+ _('Display game lobbies if unable to join a specific one.'),
+ '',
+ true
+ )
+ .setDefaultValue('yes')
+ .setHelpPath('/all- | Extensions/Multiplayer/JsExtension.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Added action "Join a specific lobby by its ID" and expression "Current lobby ID" | 7,694 | 4ian/GDevelop | 10,154 | JavaScript | Jurfix | |
target: 'object',
});
// Events based object children:
const eventsBasedObject = project.hasEventsBasedObject(
objectConfiguration.getType()
)
? project.getEventsBasedObject(objectConfiguration.getType())
: null;
const customObjectConfiguration = eventsBasedObject
? gd.asCustomObjectConfiguration(objectConfiguration)
: null;
const variantName = customObjectConfiguration
? getVariantName(eventsBasedObject, customObjectConfiguration)
: '';
const shouldDisplayEventsBasedObjectChildren =
customObjectConfiguration &&
(customObjectConfiguration.isForcedToOverrideEventsBasedObjectChildrenConfiguration() ||
(!variantName &&
customObjectConfiguration.isMarkedAsOverridingEventsBasedObjectChildrenConfiguration()));
const helpLink = getHelpLink(objectMetadata.getHelpPath());
const openFullEditor = React.useCallback(
() => onEditObject(object, 'properties'),
[object, onEditObject]
);
return (
<ErrorBoundary
componentTitle={<Trans>Object properties</Trans>}
scope="scene-editor-object-properties"
>
<ScrollView
autoHideScrollbar
style={styles.scrollView}
key={objects.map((instance: gdObject) => '' + instance.ptr).join(';')}
>
<Column expand noMargin id="object-properties-editor" noOverflowParent>
<ColumnStackLayout expand noOverflowParent>
<LineStackLayout
noMargin
alignItems="center"
justifyContent="space-between"
>
<LineStackLayout noMargin alignItems="center">
{is3DObject ? (
<Object3d style={styles.icon} />
) : (
<Object2d style={styles.icon} /> | No issues found. | target: 'object',
});
// Events based object children:
const eventsBasedObject = project.hasEventsBasedObject(
objectConfiguration.getType()
)
? project.getEventsBasedObject(objectConfiguration.getType())
: null;
const customObjectConfiguration = eventsBasedObject
? gd.asCustomObjectConfiguration(objectConfiguration)
: null;
const variantName = customObjectConfiguration
? getVariantName(eventsBasedObject, customObjectConfiguration)
: '';
const shouldDisplayEventsBasedObjectChildren =
customObjectConfiguration &&
(customObjectConfiguration.isForcedToOverrideEventsBasedObjectChildrenConfiguration() ||
(!variantName &&
customObjectConfiguration.isMarkedAsOverridingEventsBasedObjectChildrenConfiguration()));
const helpLink = getHelpLink(objectMetadata.getHelpPath());
const openFullEditor = React.useCallback(
() => onEditObject(object, 'properties'),
[object, onEditObject]
);
return (
<ErrorBoundary
componentTitle={<Trans>Object properties</Trans>}
scope="scene-editor-object-properties"
>
<ScrollView
autoHideScrollbar
style={styles.scrollView}
key={objects.map((instance: gdObject) => '' + instance.ptr).join(';')}
>
<Column expand noMargin id="object-properties-editor" noOverflowParent>
<ColumnStackLayout expand noOverflowParent>
<LineStackLayout
noMargin
alignItems="center"
justifyContent="space-between"
>
<LineStackLayout noMargin alignItems="center">
{is3DObject ? (
<Object3d style={styles.icon} />
) : (
<Object2d style={styles.icon} /> | @@ -53,6 +53,7 @@ import Window from '../../Utils/Window';
import CompactTextField from '../../UI/CompactTextField';
import { textEllipsisStyle } from '../../UI/TextEllipsis';
import Link from '../../UI/Link';
+import { getVariantName } from '../Editors/CustomObjectPropertiesEditor';
const gd: libGDevelop = global.gd;
@@ -375,11 +376,15 @@ export const CompactObjectPropertiesEditor = ({
const customObjectConfiguration = eventsBasedObject
? gd.asCustomObjectConfiguration(objectConfiguration)
: null;
+ const variantName = customObjectConfiguration
+ ? getVariantName(eventsBasedObject, customObjectConfiguration)
+ : '';
const shouldDisplayEventsBasedObjectChildren =
customObjectConfiguration &&
(customObjectConfiguration.isForcedToOverrideEventsBasedObjectChildrenConfiguration() ||
- customObjectConfiguration.isMarkedAsOverridingEventsBasedObjectChildrenConfiguration());
+ (!variantName &&
+ customObjectConfiguration.isMarkedAsOverridingEventsBasedObjectChildrenConfiguration()));
const helpLink = getHelpLink(objectMetadata.getHelpPath());
@@ -519,7 +524,6 @@ export const CompactObjectPropertiesEditor = ({
project={project}
resourceManagementProps={resourceManagementProps}
unsavedChanges={unsavedChanges}
- eventsBasedObject={eventsBasedObject}
customObjectConfiguration={
customObjectConfiguration
} | newIDE/app/src/ObjectEditor/CompactObjectPropertiesEditor/index.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Various fixes for variants | 7,739 | 4ian/GDevelop | 10,154 | JavaScript | D8H | |
if (conditionInverted) predicate = GenerateNegatedPredicate(predicate);
// Generate whole condition code
conditionCode +=
"for (var i = 0, k = 0, l = " + GetObjectListName(objectName, context) +
".length;i<l;++i) {\n";
conditionCode += " if ( " + predicate + " ) {\n";
conditionCode += " " +
GenerateBooleanFullName(returnBoolean, context) +
" = true;\n";
conditionCode += " " + GetObjectListName(objectName, context) +
"[k] = " + GetObjectListName(objectName, context) + "[i];\n";
conditionCode += " ++k;\n";
conditionCode += " }\n";
conditionCode += "}\n";
conditionCode += GetObjectListName(objectName, context) + ".length = k;\n";
return conditionCode;
}
gd::String EventsCodeGenerator::GenerateBehaviorCondition(
const gd::String& objectName,
const gd::String& behaviorName,
const gd::BehaviorMetadata& autoInfo,
const std::vector<gd::String>& arguments,
const gd::InstructionMetadata& instrInfos,
const gd::String& returnBoolean,
bool conditionInverted,
gd::EventsCodeGenerationContext& context) {
gd::String conditionCode;
// Prepare call
gd::String objectFunctionCallNamePart =
GetObjectListName(objectName, context) + "[i].getBehavior(" +
GenerateGetBehaviorNameCode(behaviorName) + ")." +
instrInfos.codeExtraInformation.functionCallName;
// Create call
gd::String predicate;
if ((instrInfos.codeExtraInformation.type == "number" ||
instrInfos.codeExtraInformation.type == "string")) {
predicate = GenerateRelationalOperatorCall(
instrInfos, arguments, objectFunctionCallNamePart, 2);
} else {
predicate = objectFunctionCallNamePart + "(" +
GenerateArgumentsList(arguments, 2) + ")";
}
if (conditionInverted) predicate = GenerateNegatedPredicate(predicate);
// Verify that object has behavior.
vector<gd::String> behaviors = | No issues found. | if (conditionInverted) predicate = GenerateNegatedPredicate(predicate);
// Generate whole condition code
conditionCode +=
"for (var i = 0, k = 0, l = " + GetObjectListName(objectName, context) +
".length;i<l;++i) {\n";
conditionCode += " if ( " + predicate + " ) {\n";
conditionCode += " " +
GenerateBooleanFullName(returnBoolean, context) +
" = true;\n";
conditionCode += " " + GetObjectListName(objectName, context) +
"[k] = " + GetObjectListName(objectName, context) + "[i];\n";
conditionCode += " ++k;\n";
conditionCode += " }\n";
conditionCode += "}\n";
conditionCode += GetObjectListName(objectName, context) + ".length = k;\n";
return conditionCode;
}
gd::String EventsCodeGenerator::GenerateBehaviorCondition(
const gd::String& objectName,
const gd::String& behaviorName,
const gd::BehaviorMetadata& autoInfo,
const std::vector<gd::String>& arguments,
const gd::InstructionMetadata& instrInfos,
const gd::String& returnBoolean,
bool conditionInverted,
gd::EventsCodeGenerationContext& context) {
gd::String conditionCode;
// Prepare call
gd::String objectFunctionCallNamePart =
GetObjectListName(objectName, context) + "[i].getBehavior(" +
GenerateGetBehaviorNameCode(behaviorName) + ")." +
instrInfos.codeExtraInformation.functionCallName;
// Create call
gd::String predicate;
if ((instrInfos.codeExtraInformation.type == "number" ||
instrInfos.codeExtraInformation.type == "string")) {
predicate = GenerateRelationalOperatorCall(
instrInfos, arguments, objectFunctionCallNamePart, 2);
} else {
predicate = objectFunctionCallNamePart + "(" +
GenerateArgumentsList(arguments, 2) + ")";
}
if (conditionInverted) predicate = GenerateNegatedPredicate(predicate);
// Verify that object has behavior.
vector<gd::String> behaviors = | @@ -1228,14 +1228,11 @@ gd::String EventsCodeGenerator::GenerateParameterCodes(
// Code only parameter type
else if (metadata.GetType() == "objectsContext") {
argOutput =
- "(typeof eventsFunctionContext !== 'undefined' ? eventsFunctionContext "
- ": runtimeScene)";
+ HasProjectAndLayout() ? "runtimeScene" : "eventsFunctionContext";
}
// Code only parameter type
else if (metadata.GetType() == "eventsFunctionContext") {
- argOutput =
- "(typeof eventsFunctionContext !== 'undefined' ? eventsFunctionContext "
- ": undefined)";
+ argOutput = HasProjectAndLayout() ? "null" : "eventsFunctionContext";
} else
return gd::EventsCodeGenerator::GenerateParameterCodes(
parameter, | GDJS/GDJS/Events/CodeGeneration/EventsCodeGenerator.cpp | 0 | C++ | 1 | none | 16 | 51 | 51 | true | Optimize event-function calls | 7,758 | 4ian/GDevelop | 10,154 | JavaScript | D8H | |
}
/**
* Get the font size of the characters of the object.
*/
getCharacterSize(): number {
return this._characterSize;
}
/**
* Set the font size for characters of the object.
* @param newSize The new font size for the text.
*/
setCharacterSize(newSize: number): void {
if (newSize <= 1) {
newSize = 1;
}
this._characterSize = newSize;
this._renderer.updateStyle();
}
/**
* Get the line height of the text.
*/
getLineHeight(): float {
return this._lineHeight;
}
/**
* Set the line height of the text.
* @param value The new line height for the text.
*/
setLineHeight(value: float): void {
this._lineHeight = value;
this._renderer.updateStyle();
}
/**
* Set the name of the resource to use for the font.
* @param fontResourceName The name of the font resource.
*/
setFontName(fontResourceName: string): void {
this._fontName = fontResourceName;
this._renderer.updateStyle();
}
/**
* Return true if the text is bold.
*/
isBold(): boolean {
return this._bold; | No issues found. | }
/**
* Get the font size of the characters of the object.
*/
getCharacterSize(): number {
return this._characterSize;
}
/**
* Set the font size for characters of the object.
* @param newSize The new font size for the text.
*/
setCharacterSize(newSize: number): void {
if (newSize <= 1) {
newSize = 1;
}
this._characterSize = newSize;
this._renderer.updateStyle();
}
/**
* Get the line height of the text.
*/
getLineHeight(): float {
return this._lineHeight;
}
/**
* Set the line height of the text.
* @param value The new line height for the text.
*/
setLineHeight(value: float): void {
this._lineHeight = value;
this._renderer.updateStyle();
}
/**
* Set the name of the resource to use for the font.
* @param fontResourceName The name of the font resource.
*/
setFontName(fontResourceName: string): void {
this._fontName = fontResourceName;
this._renderer.updateStyle();
}
/**
* Return true if the text is bold.
*/
isBold(): boolean {
return this._bold; | @@ -602,16 +602,10 @@ namespace gdjs {
/**
* Change the text color.
- * @param colorString color as a "R;G;B" string, for example: "255;0;0"
+ * @param rgbOrHexColor color as a "R;G;B" string, for example: "255;0;0"
*/
- setColor(colorString: string): void {
- const color = colorString.split(';');
- if (color.length < 3) {
- return;
- }
- this._color[0] = parseInt(color[0], 10);
- this._color[1] = parseInt(color[1], 10);
- this._color[2] = parseInt(color[2], 10);
+ setColor(rgbOrHexColor: string): void {
+ this._color = gdjs.rgbOrHexToRGBColor(rgbOrHexColor);
this._useGradient = false;
this._renderer.updateStyle();
}
@@ -720,18 +714,12 @@ namespace gdjs {
/**
* Set the outline for the text object.
- * @param str color as a "R;G;B" string, for example: "255;0;0"
+ * @param rgbOrHexColor color as a "R;G;B" string, for example: "255;0;0"
* @param thickness thickness of the outline (0 = disabled)
* @deprecated Prefer independent setters.
*/
- setOutline(str: string, thickness: number): void {
- const color = str.split(';');
- if (color.length < 3) {
- return;
- }
- this._outlineColor[0] = parseInt(color[0], 10);
- this._outlineColor[1] = parseInt(color[1], 10);
- this._outlineColor[2] = parseInt(color[2], 10);
+ setOutline(rgbOrHexColor: string, thickness: number): void {
+ this._outlineColor = gdjs.rgbOrHexToRGBColor(rgbOrHexColor);
this._outlineThickness = thickness;
this._renderer.updateStyle();
}
@@ -773,25 +761,19 @@ namespace gdjs {
/**
* Set the shadow for the text object.
- * @param str color as a "R;G;B" string, for example: "255;0;0"
+ * @param rgbOrHexColor color as a "R;G;B" string, for example: "255;0;0"
* @param distance distance between the shadow and the text, in pixels.
* @param blur amount of shadow blur, in pixels.
* | Extensions/TextObject/textruntimeobject.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | Fix the tint action of Sprite to handle floating point color components | 7,772 | 4ian/GDevelop | 10,154 | JavaScript | D8H | |
/**
* Return a PIXI texture which can be used as a placeholder when no
* suitable texture can be found.
*/
getInvalidPIXITexture() {
return this._invalidTexture;
}
/**
* Load the specified resources, so that textures are loaded and can then be
* used by calling `getPIXITexture`.
*/
async loadResource(resourceName: string): Promise<void> {
const resource = this._resourceLoader.getResource(resourceName);
if (!resource) {
logger.warn(
'Unable to find texture for resource "' + resourceName + '".'
);
return;
}
await this._loadTexture(resource);
}
async processResource(resourceName: string): Promise<void> {
// Do nothing because images are light enough to be parsed in background.
}
/**
* Load the specified resources, so that textures are loaded and can then be
* used by calling `getPIXITexture`.
* @param onProgress Callback called each time a new file is loaded.
*/
async _loadTexture(resource: ResourceData): Promise<void> {
if (this._loadedTextures.get(resource)) {
return;
}
try {
if (resource.kind === 'video') {
// For videos, we want to preload them so they are available as soon as we want to use them.
// We cannot use Pixi.assets.load() as it does not allow passing options (autoplay) to the resource loader.
// Pixi.Texture.from() does not return a promise, so we need to ensure we look at the 'loaded' event of the baseTexture,
// to continue, otherwise if we try to play the video too soon (at the beginning of scene for instance),
// it will fail.
await new Promise<void>((resolve, reject) => {
const texture = PIXI.Texture.from(
this._resourceLoader.getFullUrl(resource.file),
{
resourceOptions: {
crossorigin: this._resourceLoader.checkIfCredentialsRequired(
resource.file
) | No issues found. | /**
* Return a PIXI texture which can be used as a placeholder when no
* suitable texture can be found.
*/
getInvalidPIXITexture() {
return this._invalidTexture;
}
/**
* Load the specified resources, so that textures are loaded and can then be
* used by calling `getPIXITexture`.
*/
async loadResource(resourceName: string): Promise<void> {
const resource = this._resourceLoader.getResource(resourceName);
if (!resource) {
logger.warn(
'Unable to find texture for resource "' + resourceName + '".'
);
return;
}
await this._loadTexture(resource);
}
async processResource(resourceName: string): Promise<void> {
// Do nothing because images are light enough to be parsed in background.
}
/**
* Load the specified resources, so that textures are loaded and can then be
* used by calling `getPIXITexture`.
* @param onProgress Callback called each time a new file is loaded.
*/
async _loadTexture(resource: ResourceData): Promise<void> {
if (this._loadedTextures.get(resource)) {
return;
}
try {
if (resource.kind === 'video') {
// For videos, we want to preload them so they are available as soon as we want to use them.
// We cannot use Pixi.assets.load() as it does not allow passing options (autoplay) to the resource loader.
// Pixi.Texture.from() does not return a promise, so we need to ensure we look at the 'loaded' event of the baseTexture,
// to continue, otherwise if we try to play the video too soon (at the beginning of scene for instance),
// it will fail.
await new Promise<void>((resolve, reject) => {
const texture = PIXI.Texture.from(
this._resourceLoader.getFullUrl(resource.file),
{
resourceOptions: {
crossorigin: this._resourceLoader.checkIfCredentialsRequired(
resource.file
) | @@ -55,7 +55,7 @@ namespace gdjs {
* Map associating a resource name to the loaded Three.js texture.
*/
private _loadedThreeTextures: Hashtable<THREE.Texture>;
- private _loadedThreeMaterials: Hashtable<THREE.Material>;
+ private _loadedThreeMaterials = new ThreeMaterialCache();
private _diskTextures = new Map<float, PIXI.Texture>();
private _rectangleTextures = new Map<string, PIXI.Texture>();
@@ -73,7 +73,6 @@ namespace gdjs {
{ width: 192, height: 192 }
);
this._loadedThreeTextures = new Hashtable();
- this._loadedThreeMaterials = new Hashtable();
}
getResourceKinds(): ResourceKind[] {
@@ -224,38 +223,37 @@ namespace gdjs {
*/
getThreeMaterial(
resourceName: string,
- {
- useTransparentTexture,
- forceBasicMaterial,
- vertexColors,
- }: {
+ options: {
useTransparentTexture: boolean;
forceBasicMaterial: boolean;
vertexColors: boolean;
}
): THREE.Material {
- const cacheKey = `${resourceName}|${useTransparentTexture ? 1 : 0}|${
- forceBasicMaterial ? 1 : 0
- }|${vertexColors ? 1 : 0}`;
-
- const loadedThreeMaterial = this._loadedThreeMaterials.get(cacheKey);
+ const loadedThreeMaterial = this._loadedThreeMaterials.get(
+ resourceName,
+ options
+ );
if (loadedThreeMaterial) return loadedThreeMaterial;
- const material = forceBasicMaterial
+ const material = options.forceBasicMaterial
? new THREE.MeshBasicMaterial({
map: this.getThreeTexture(resourceName),
- side: useTransparentTexture ? THREE.DoubleSide : THREE.FrontSide,
- transparent: useTransparentTexture,
- vertexColors,
+ side: options.useTransparentTexture
+ ? THREE.DoubleSide
+ : THREE.FrontSide,
+ transparent: options.useTransparentTexture,
+ vertexColors: options.ve | GDJS/Runtime/pixi-renderers/pixi-image-manager.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | Fix cached materials not being cleared when unloading resources | 7,780 | 4ian/GDevelop | 10,154 | JavaScript | D8H | |
extensionShortHeader
);
installedOrImportedExtensionName = wasExtensionInstalledOrImported
? extensionShortHeader.name
: null;
} else {
installedOrImportedExtensionName = await importExtension(
i18n,
eventsFunctionsExtensionsState,
project,
onInstallExtension,
showConfirmation,
showAlert
);
}
if (installedOrImportedExtensionName) {
setExtensionWasInstalled(true);
onExtensionInstalled([installedOrImportedExtensionName]);
return true;
}
return false;
} finally {
setIsInstalling(false);
}
};
const eventsFunctionsExtensionOpener = eventsFunctionsExtensionsState.getEventsFunctionsExtensionOpener();
return (
<I18n>
{({ i18n }) => (
<Dialog
title={<Trans>Search for New Extensions</Trans>}
id="extension-search-dialog"
fullHeight
actions={[
<FlatButton
id="close-button"
key="close"
label={<Trans>Close</Trans>}
primary
onClick={onClose}
disabled={isInstalling}
/>,
]}
secondaryActions={[
<HelpButton key="help" helpPagePath="/extensions/search" />,
eventsFunctionsExtensionOpener ? (
<FlatButton | No issues found. | extensionShortHeader
);
installedOrImportedExtensionName = wasExtensionInstalledOrImported
? extensionShortHeader.name
: null;
} else {
installedOrImportedExtensionName = await importExtension(
i18n,
eventsFunctionsExtensionsState,
project,
onInstallExtension,
showConfirmation,
showAlert
);
}
if (installedOrImportedExtensionName) {
setExtensionWasInstalled(true);
onExtensionInstalled([installedOrImportedExtensionName]);
return true;
}
return false;
} finally {
setIsInstalling(false);
}
};
const eventsFunctionsExtensionOpener = eventsFunctionsExtensionsState.getEventsFunctionsExtensionOpener();
return (
<I18n>
{({ i18n }) => (
<Dialog
title={<Trans>Search for New Extensions</Trans>}
id="extension-search-dialog"
fullHeight
actions={[
<FlatButton
id="close-button"
key="close"
label={<Trans>Close</Trans>}
primary
onClick={onClose}
disabled={isInstalling}
/>,
]}
secondaryActions={[
<HelpButton key="help" helpPagePath="/extensions/search" />,
eventsFunctionsExtensionOpener ? (
<FlatButton | @@ -20,6 +20,7 @@ import { useResponsiveWindowSize } from '../../UI/Responsive/ResponsiveWindowMea
import Download from '../../UI/CustomSvgIcons/Download';
import Add from '../../UI/CustomSvgIcons/Add';
import ErrorBoundary from '../../UI/ErrorBoundary';
+import useAlertDialog from '../../UI/Alert/useAlertDialog';
type Props = {|
project: gdProject,
@@ -54,6 +55,7 @@ const ExtensionsSearchDialog = ({
TRIVIAL_FIRST_EXTENSION,
installExtension
);
+ const { showConfirmation, showAlert } = useAlertDialog();
const installOrImportExtension = async (
i18n: I18nType,
@@ -78,7 +80,9 @@ const ExtensionsSearchDialog = ({
i18n,
eventsFunctionsExtensionsState,
project,
- onInstallExtension
+ onInstallExtension,
+ showConfirmation,
+ showAlert
);
}
| newIDE/app/src/AssetStore/ExtensionStore/ExtensionsSearchDialog.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Forbid to import an extension which has the same name as a built-in one | 7,822 | 4ian/GDevelop | 10,154 | JavaScript | D8H | |
<span>
<Column>
<DragHandleIcon />
</Column>
</span>
)}
<ResponsiveLineStackLayout expand noMargin>
<Line noMargin expand alignItems="center">
<SemiControlledTextField
margin="none"
commitOnBlur
translatableHintText={t`Enter the property name`}
value={property.getName()}
onChange={newName => {
if (newName === property.getName())
return;
const projectScopedContainers = projectScopedContainersAccessor.get();
const validatedNewName = getValidatedPropertyName(
properties,
projectScopedContainers,
newName
);
onRenameProperty(
property.getName(),
validatedNewName
);
property.setName(validatedNewName);
forceUpdate();
onPropertiesUpdated &&
onPropertiesUpdated();
}}
fullWidth
/>
</Line>
<Line
noMargin
alignItems="center"
justifyContent="flex-end"
>
<SelectField
margin="none"
disabled={
property.getType() === 'Behavior' &&
!property.isHidden()
}
value={
property.isHidden()
? 'Hidden'
: property.isDeprecated() | No issues found. | <span>
<Column>
<DragHandleIcon />
</Column>
</span>
)}
<ResponsiveLineStackLayout expand noMargin>
<Line noMargin expand alignItems="center">
<SemiControlledTextField
margin="none"
commitOnBlur
translatableHintText={t`Enter the property name`}
value={property.getName()}
onChange={newName => {
if (newName === property.getName())
return;
const projectScopedContainers = projectScopedContainersAccessor.get();
const validatedNewName = getValidatedPropertyName(
properties,
projectScopedContainers,
newName
);
onRenameProperty(
property.getName(),
validatedNewName
);
property.setName(validatedNewName);
forceUpdate();
onPropertiesUpdated &&
onPropertiesUpdated();
}}
fullWidth
/>
</Line>
<Line
noMargin
alignItems="center"
justifyContent="flex-end"
>
<SelectField
margin="none"
disabled={
property.getType() === 'Behavior' &&
!property.isHidden()
}
value={
property.isHidden()
? 'Hidden'
: property.isDeprecated() | @@ -15,7 +15,7 @@ import ElementWithMenu from '../UI/Menu/ElementWithMenu';
import SemiControlledTextField from '../UI/SemiControlledTextField';
import newNameGenerator from '../Utils/NewNameGenerator';
import { ResponsiveLineStackLayout, ColumnStackLayout } from '../UI/Layout';
-import StringArrayEditor from '../StringArrayEditor';
+import ChoicesEditor, { type Choice } from '../ChoicesEditor';
import ColorField from '../UI/ColorField';
import BehaviorTypeSelector from '../BehaviorTypeSelector';
import SemiControlledAutoComplete from '../UI/SemiControlledAutoComplete';
@@ -124,9 +124,13 @@ const getValidatedPropertyName = (
return safeAndUniqueNewName;
};
-const getExtraInfoArray = (property: gdNamedPropertyDescriptor) => {
- const extraInfoVector = property.getExtraInfo();
- return extraInfoVector.toJSArray();
+const getChoicesArray = (
+ property: gdNamedPropertyDescriptor
+): Array<Choice> => {
+ return mapVector(property.getChoices(), choice => ({
+ value: choice.getValue(),
+ label: choice.getLabel(),
+ }));
};
export default function EventsBasedBehaviorPropertiesEditor({
@@ -397,17 +401,18 @@ export default function EventsBasedBehaviorPropertiesEditor({
[properties, forceUpdate, onPropertiesUpdated]
);
- const setChoiceExtraInfo = React.useCallback(
+ const setChoices = React.useCallback(
(property: gdNamedPropertyDescriptor) => {
- return (newExtraInfo: Array<string>) => {
- const defaultValueIndex = getExtraInfoArray(property).indexOf(
- property.getValue()
+ return (choices: Array<Choice>) => {
+ property.clearChoices();
+ for (const choice of choices) {
+ property.addChoice(choice.value, choice.label);
+ }
+ property.setValue(
+ getChoicesArray(property).includes(property.getValue())
+ ? property.getValue()
+ : ''
);
- const vectorString = new gd.VectorString();
- newExtraInfo.forEach(item => vect | newIDE/app/src/EventsBasedBehaviorEditor/EventsBasedBehaviorPropertiesEditor.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Allow extensions to define labels for properties with string selectors | 7,825 | 4ian/GDevelop | 10,154 | JavaScript | D8H | |
'\n' +
(extension.getHelpPath() ? `\n[Read more...](${helpPageUrl})\n` : ``) +
'\n' +
`!!! tip
Learn [how to install new extensions](/gdevelop5/extensions/search) by following a step-by-step guide.` +
'\n',
};
};
/** @returns {RawText} */
const generateExtensionFooterText = ({ extension }) => {
return {
text:
`
---
*This page is an auto-generated reference page about the **${extension.getFullName()}** extension, made by the community of [GDevelop, the open-source, cross-platform game engine designed for everyone](https://gdevelop.io/).*` +
' ' +
'Learn more about [all GDevelop community-made extensions here](/gdevelop5/extensions).',
};
};
/**
* Generate the metadata for the events based extension
* @param {any} project A project containing of the extensions (gdProject)
* @param {any} eventsFunctionsExtension An extension (gdEventsFunctionsExtension)
* @returns {any} the extension metadata (gdPlatformExtension)
*/
const generateEventsFunctionExtensionMetadata = (
gd,
project,
eventsFunctionsExtension
) => {
const extension = new gd.PlatformExtension();
gd.MetadataDeclarationHelper.declareExtension(
extension,
eventsFunctionsExtension
);
// Generate all behaviors and their functions
mapVector(
eventsFunctionsExtension.getEventsBasedBehaviors(),
eventsBasedBehavior => {
const behaviorMethodMangledNames = new gd.MapStringString();
gd.MetadataDeclarationHelper.generateBehaviorMetadata(
project,
extension,
eventsFunctionsExtension,
eventsBasedBehavior,
behaviorMethodMangledNames
); | No issues found. | '\n' +
(extension.getHelpPath() ? `\n[Read more...](${helpPageUrl})\n` : ``) +
'\n' +
`!!! tip
Learn [how to install new extensions](/gdevelop5/extensions/search) by following a step-by-step guide.` +
'\n',
};
};
/** @returns {RawText} */
const generateExtensionFooterText = ({ extension }) => {
return {
text:
`
---
*This page is an auto-generated reference page about the **${extension.getFullName()}** extension, made by the community of [GDevelop, the open-source, cross-platform game engine designed for everyone](https://gdevelop.io/).*` +
' ' +
'Learn more about [all GDevelop community-made extensions here](/gdevelop5/extensions).',
};
};
/**
* Generate the metadata for the events based extension
* @param {any} project A project containing of the extensions (gdProject)
* @param {any} eventsFunctionsExtension An extension (gdEventsFunctionsExtension)
* @returns {any} the extension metadata (gdPlatformExtension)
*/
const generateEventsFunctionExtensionMetadata = (
gd,
project,
eventsFunctionsExtension
) => {
const extension = new gd.PlatformExtension();
gd.MetadataDeclarationHelper.declareExtension(
extension,
eventsFunctionsExtension
);
// Generate all behaviors and their functions
mapVector(
eventsFunctionsExtension.getEventsBasedBehaviors(),
eventsBasedBehavior => {
const behaviorMethodMangledNames = new gd.MapStringString();
gd.MetadataDeclarationHelper.generateBehaviorMetadata(
project,
extension,
eventsFunctionsExtension,
eventsBasedBehavior,
behaviorMethodMangledNames
); | @@ -26,7 +26,7 @@ const { mapVector, mapFor } = require('./lib/MapFor');
/** @typedef {import("./lib/ExtensionReferenceGenerator.js").RawText} RawText */
-/** @typedef {{ tier: 'community' | 'reviewed', shortDescription: string, authorIds: Array<string>, authors?: Array<{id: string, username: string}>, extensionNamespace: string, fullName: string, name: string, version: string, gdevelopVersion?: string, url: string, headerUrl: string, tags: Array<string>, category: string, previewIconUrl: string, eventsBasedBehaviorsCount: number, eventsFunctionsCount: number}} ExtensionShortHeader */
+/** @typedef {{ tier: 'community' | 'experimental' | 'reviewed', shortDescription: string, authorIds: Array<string>, authors?: Array<{id: string, username: string}>, extensionNamespace: string, fullName: string, name: string, version: string, gdevelopVersion?: string, url: string, headerUrl: string, tags: Array<string>, category: string, previewIconUrl: string, eventsBasedBehaviorsCount: number, eventsFunctionsCount: number}} ExtensionShortHeader */
const extensionShortHeadersUrl =
'https://api.gdevelop-app.com/asset/extension-short-header';
@@ -174,14 +174,14 @@ const sortKeys = table => {
* @param {any} project (gdProject)
* @param {any} extension The extension (gdEventsFunctionsExtension)
* @param {ExtensionShortHeader} extensionShortHeader
- * @param {boolean} isCommunity The tier
+ * @param {boolean} isExperimental The tier
*/
const createExtensionReferencePage = async (
gd,
project,
extension,
extensionShortHeader,
- isCommunity
+ isExperimental
) => {
const extensionMetadata = generateEventsFunctionExtensionMetadata(
gd,
@@ -196,7 +196,7 @@ const createExtensionReferencePage = async (
generateExtensionHeaderText(
reference,
extensionShortHeader,
- isCommunity
+ isExperimental
),
generateExtensionFooterText
)
@@ -219,13 +219,13 @@ const createExtensionReferencePage = | newIDE/app/scripts/extract-extensions-document.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Rename "community" extensions as "experimental" extensions | 7,828 | 4ian/GDevelop | 10,154 | JavaScript | D8H | |
#include "GDCore/Tools/Log.h"
namespace gd {
VariablesContainer EventsVariableInstructionTypeSwitcher::nullVariablesContainer;
bool EventsVariableInstructionTypeSwitcher::DoVisitInstruction(gd::Instruction& instruction,
bool isCondition) {
const auto& metadata = isCondition
? gd::MetadataProvider::GetConditionMetadata(
platform, instruction.GetType())
: gd::MetadataProvider::GetActionMetadata(
platform, instruction.GetType());
gd::ParameterMetadataTools::IterateOverParametersWithIndex(
instruction.GetParameters(), metadata.GetParameters(),
[&](const gd::ParameterMetadata ¶meterMetadata,
const gd::Expression ¶meterValue, size_t parameterIndex,
const gd::String &lastObjectName, size_t lastObjectIndex) {
const gd::String& type = parameterMetadata.GetType();
if (!gd::ParameterMetadata::IsExpression("variable", type) ||
!gd::VariableInstructionSwitcher::IsSwitchableVariableInstruction(
instruction.GetType())) {
return;
}
const auto variableName =
gd::ExpressionVariableNameFinder::GetVariableName(
*parameterValue.GetRootNode());
const gd::VariablesContainer *variablesContainer = nullptr;
if (type == "objectvar") {
const auto &objectsContainersList =
GetProjectScopedContainers().GetObjectsContainersList();
if (objectsContainersList.HasObjectOrGroupWithVariableNamed(
lastObjectName, variableName) !=
gd::ObjectsContainersList::VariableExistence::DoesNotExist) {
variablesContainer =
GetProjectScopedContainers()
.GetObjectsContainersList()
.GetObjectOrGroupVariablesContainer(lastObjectName);
}
} else if (type == "variableOrProperty") {
variablesContainer =
&GetProjectScopedContainers()
.GetVariablesContainersList()
.GetVariablesContainerFromVariableOrPropertyName(
variableName);
} else {
if (GetProjectScopedContainers().GetVariablesContainersList().Has(
variableName)) { | No issues found. | #include "GDCore/Tools/Log.h"
namespace gd {
VariablesContainer EventsVariableInstructionTypeSwitcher::nullVariablesContainer;
bool EventsVariableInstructionTypeSwitcher::DoVisitInstruction(gd::Instruction& instruction,
bool isCondition) {
const auto& metadata = isCondition
? gd::MetadataProvider::GetConditionMetadata(
platform, instruction.GetType())
: gd::MetadataProvider::GetActionMetadata(
platform, instruction.GetType());
gd::ParameterMetadataTools::IterateOverParametersWithIndex(
instruction.GetParameters(), metadata.GetParameters(),
[&](const gd::ParameterMetadata ¶meterMetadata,
const gd::Expression ¶meterValue, size_t parameterIndex,
const gd::String &lastObjectName, size_t lastObjectIndex) {
const gd::String& type = parameterMetadata.GetType();
if (!gd::ParameterMetadata::IsExpression("variable", type) ||
!gd::VariableInstructionSwitcher::IsSwitchableVariableInstruction(
instruction.GetType())) {
return;
}
const auto variableName =
gd::ExpressionVariableNameFinder::GetVariableName(
*parameterValue.GetRootNode());
const gd::VariablesContainer *variablesContainer = nullptr;
if (type == "objectvar") {
const auto &objectsContainersList =
GetProjectScopedContainers().GetObjectsContainersList();
if (objectsContainersList.HasObjectOrGroupWithVariableNamed(
lastObjectName, variableName) !=
gd::ObjectsContainersList::VariableExistence::DoesNotExist) {
variablesContainer =
GetProjectScopedContainers()
.GetObjectsContainersList()
.GetObjectOrGroupVariablesContainer(lastObjectName);
}
} else if (type == "variableOrProperty") {
variablesContainer =
&GetProjectScopedContainers()
.GetVariablesContainersList()
.GetVariablesContainerFromVariableOrPropertyName(
variableName);
} else {
if (GetProjectScopedContainers().GetVariablesContainersList().Has(
variableName)) { | @@ -42,18 +42,16 @@ bool EventsVariableInstructionTypeSwitcher::DoVisitInstruction(gd::Instruction&
platform, instruction.GetType());
gd::ParameterMetadataTools::IterateOverParametersWithIndex(
- instruction.GetParameters(),
- metadata.GetParameters(),
- [&](const gd::ParameterMetadata& parameterMetadata,
- const gd::Expression& parameterValue,
- size_t parameterIndex,
- const gd::String& lastObjectName) {
+ instruction.GetParameters(), metadata.GetParameters(),
+ [&](const gd::ParameterMetadata ¶meterMetadata,
+ const gd::Expression ¶meterValue, size_t parameterIndex,
+ const gd::String &lastObjectName, size_t lastObjectIndex) {
const gd::String& type = parameterMetadata.GetType();
if (!gd::ParameterMetadata::IsExpression("variable", type) ||
!gd::VariableInstructionSwitcher::IsSwitchableVariableInstruction(
instruction.GetType())) {
- return;
+ return;
}
const auto variableName =
gd::ExpressionVariableNameFinder::GetVariableName(
@@ -72,10 +70,11 @@ bool EventsVariableInstructionTypeSwitcher::DoVisitInstruction(gd::Instruction&
.GetObjectOrGroupVariablesContainer(lastObjectName);
}
} else if (type == "variableOrProperty") {
- variablesContainer =
- &GetProjectScopedContainers()
- .GetVariablesContainersList()
- .GetVariablesContainerFromVariableOrPropertyName(variableName);
+ variablesContainer =
+ &GetProjectScopedContainers()
+ .GetVariablesContainersList()
+ .GetVariablesContainerFromVariableOrPropertyName(
+ variableName);
} else {
if (GetProjectScopedContainers().GetVariablesContainersList().Has(
variableName)) { | Core/GDCore/IDE/Events/EventsVariableInstructionTypeSwitcher.cpp | 0 | C++ | 1 | none | 16 | 51 | 51 | true | Fix a crash at runtime when behaviors are missing in functions | 7,830 | 4ian/GDevelop | 10,154 | JavaScript | D8H | |
if (resourceName === '') {
return this._invalidTexture;
}
const resource = this._getImageResource(resourceName);
if (!resource) {
logger.warn(
'Unable to find video texture for resource "' + resourceName + '".'
);
return this._invalidTexture;
}
const texture = this._loadedTextures.get(resource);
if (!texture) {
return this._invalidTexture;
}
return texture;
}
private _getImageResource = (resourceName: string): ResourceData | null => {
const resource = this._resourceLoader.getResource(resourceName);
return resource && this.getResourceKinds().includes(resource.kind)
? resource
: null;
};
/**
* Return a PIXI texture which can be used as a placeholder when no
* suitable texture can be found.
*/
getInvalidPIXITexture() {
return this._invalidTexture;
}
/**
* Load the specified resources, so that textures are loaded and can then be
* used by calling `getPIXITexture`.
*/
async loadResource(resourceName: string): Promise<void> {
const resource = this._resourceLoader.getResource(resourceName);
if (!resource) {
logger.warn(
'Unable to find texture for resource "' + resourceName + '".'
);
return;
}
await this._loadTexture(resource);
}
async processResource(resourceName: string): Promise<void> {
// Do nothing because images are light enough to be parsed in background.
} | No issues found. | if (resourceName === '') {
return this._invalidTexture;
}
const resource = this._getImageResource(resourceName);
if (!resource) {
logger.warn(
'Unable to find video texture for resource "' + resourceName + '".'
);
return this._invalidTexture;
}
const texture = this._loadedTextures.get(resource);
if (!texture) {
return this._invalidTexture;
}
return texture;
}
private _getImageResource = (resourceName: string): ResourceData | null => {
const resource = this._resourceLoader.getResource(resourceName);
return resource && this.getResourceKinds().includes(resource.kind)
? resource
: null;
};
/**
* Return a PIXI texture which can be used as a placeholder when no
* suitable texture can be found.
*/
getInvalidPIXITexture() {
return this._invalidTexture;
}
/**
* Load the specified resources, so that textures are loaded and can then be
* used by calling `getPIXITexture`.
*/
async loadResource(resourceName: string): Promise<void> {
const resource = this._resourceLoader.getResource(resourceName);
if (!resource) {
logger.warn(
'Unable to find texture for resource "' + resourceName + '".'
);
return;
}
await this._loadTexture(resource);
}
async processResource(resourceName: string): Promise<void> {
// Do nothing because images are light enough to be parsed in background.
} | @@ -56,6 +56,11 @@ namespace gdjs {
*/
private _loadedThreeTextures: Hashtable<THREE.Texture>;
private _loadedThreeMaterials = new ThreeMaterialCache();
+ private _loadedThreeCubeTextures = new Map<string, THREE.CubeTexture>();
+ private _loadedThreeCubeTextureKeysByResourceName = new ArrayMap<
+ string,
+ string
+ >();
private _diskTextures = new Map<float, PIXI.Texture>();
private _rectangleTextures = new Map<string, PIXI.Texture>();
@@ -181,7 +186,25 @@ namespace gdjs {
if (loadedThreeTexture) {
return loadedThreeTexture;
}
+ const image = this._getImageSource(resourceName);
+ const threeTexture = new THREE.Texture(image);
+ threeTexture.magFilter = THREE.LinearFilter;
+ threeTexture.minFilter = THREE.LinearFilter;
+ threeTexture.wrapS = THREE.RepeatWrapping;
+ threeTexture.wrapT = THREE.RepeatWrapping;
+ threeTexture.colorSpace = THREE.SRGBColorSpace;
+ threeTexture.needsUpdate = true;
+
+ const resource = this._getImageResource(resourceName);
+
+ applyThreeTextureSettings(threeTexture, resource);
+ this._loadedThreeTextures.put(resourceName, threeTexture);
+
+ return threeTexture;
+ }
+
+ private _getImageSource(resourceName: string): HTMLImageElement {
// Texture is not loaded, load it now from the PixiJS texture.
// TODO (3D) - optimization: don't load the PixiJS Texture if not used by PixiJS.
// TODO (3D) - optimization: Ideally we could even share the same WebGL texture.
@@ -198,21 +221,86 @@ namespace gdjs {
`Can't load texture for resource "${resourceName}" as it's not an image.`
);
}
+ return image;
+ }
- const threeTexture = new THREE.Texture(image);
- threeTexture.magFilter = THREE.LinearFilter;
- threeTexture.minFilter = THREE.LinearFilter;
- threeTexture.wrapS = THREE.RepeatWrapping;
- threeTexture.wrapT = THREE.RepeatWrapping;
- | GDJS/Runtime/pixi-renderers/pixi-image-manager.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | Add a skybox filter | 7,843 | 4ian/GDevelop | 10,154 | JavaScript | D8H | |
setSelectedBundleListingData,
] = React.useState<?BundleListingData>(null);
const { courses, getCourseCompletion } = useCourses();
const { bundleListingDatas } = React.useContext(BundleStoreContext);
React.useEffect(
() => {
const bundleCategory = routeArguments['bundle-category'];
if (!bundleCategory || !bundleListingDatas) {
return;
}
let bundleListingData: ?BundleListingData = null;
// Open the information page of a the bundle.
if (bundleCategory) {
bundleListingData = getBundleListingDataFromCategory({
bundleListingDatas,
category: bundleCategory,
});
}
if (!bundleListingData) {
onClose();
return;
}
const priceForUsageType = bundleListingData.prices.find(
price => price.usageType === 'default'
);
sendBundleInformationOpened({
bundleName: bundleListingData.name,
bundleId: bundleListingData.id,
source: 'web-link',
priceValue: priceForUsageType && priceForUsageType.value,
priceCurrency: priceForUsageType && priceForUsageType.currency,
});
setSelectedBundleListingData(bundleListingData);
removeRouteArguments(['bundle-category']);
},
[bundleListingDatas, routeArguments, onClose, removeRouteArguments]
);
return (
<Dialog
title={null} // Let the content decide.
open
fullscreen="always-even-on-desktop"
noPadding
cannotBeDismissed
flexColumnBody
>
{!selectedBundleListingData ? ( | No issues found. | setSelectedBundleListingData,
] = React.useState<?BundleListingData>(null);
const { courses, getCourseCompletion } = useCourses();
const { bundleListingDatas } = React.useContext(BundleStoreContext);
React.useEffect(
() => {
const bundleCategory = routeArguments['bundle-category'];
if (!bundleCategory || !bundleListingDatas) {
return;
}
let bundleListingData: ?BundleListingData = null;
// Open the information page of a the bundle.
if (bundleCategory) {
bundleListingData = getBundleListingDataFromCategory({
bundleListingDatas,
category: bundleCategory,
});
}
if (!bundleListingData) {
onClose();
return;
}
const priceForUsageType = bundleListingData.prices.find(
price => price.usageType === 'default'
);
sendBundleInformationOpened({
bundleName: bundleListingData.name,
bundleId: bundleListingData.id,
source: 'web-link',
priceValue: priceForUsageType && priceForUsageType.value,
priceCurrency: priceForUsageType && priceForUsageType.currency,
});
setSelectedBundleListingData(bundleListingData);
removeRouteArguments(['bundle-category']);
},
[bundleListingDatas, routeArguments, onClose, removeRouteArguments]
);
return (
<Dialog
title={null} // Let the content decide.
open
fullscreen="always-even-on-desktop"
noPadding
cannotBeDismissed
flexColumnBody
>
{!selectedBundleListingData ? ( | @@ -0,0 +1,120 @@
+// @flow
+import { Trans } from '@lingui/macro';
+
+import React from 'react';
+import Dialog from '../UI/Dialog';
+import PlaceholderLoader from '../UI/PlaceholderLoader';
+import ErrorBoundary from '../UI/ErrorBoundary';
+import RouterContext from './RouterContext';
+import { BundleStoreContext } from '../AssetStore/Bundles/BundleStoreContext';
+import { type BundleListingData } from '../Utils/GDevelopServices/Shop';
+import { getBundleListingDataFromCategory } from '../AssetStore/AssetStoreUtils';
+import { sendBundleInformationOpened } from '../Utils/Analytics/EventSender';
+import BundleInformationPage from '../AssetStore/Bundles/BundleInformationPage';
+import useCourses from './EditorContainers/HomePage/UseCourses';
+import useSubscriptionPlans from '../Utils/UseSubscriptionPlans';
+import AuthenticatedUserContext from '../Profile/AuthenticatedUserContext';
+
+type Props = {|
+ // This dialog is not meant to be closed, but in case of an error, we provide a way to close it.
+ onClose: () => void,
+|};
+
+const StandaloneDialog = ({ onClose }: Props) => {
+ const authenticatedUser = React.useContext(AuthenticatedUserContext);
+ const {
+ routeArguments,
+ removeRouteArguments,
+ navigateToRoute,
+ } = React.useContext(RouterContext);
+ const { getSubscriptionPlansWithPricingSystems } = useSubscriptionPlans({
+ authenticatedUser,
+ includeLegacy: false,
+ });
+ const [
+ selectedBundleListingData,
+ setSelectedBundleListingData,
+ ] = React.useState<?BundleListingData>(null);
+ const { courses, getCourseCompletion } = useCourses();
+ const { bundleListingDatas } = React.useContext(BundleStoreContext);
+ React.useEffect(
+ () => {
+ const bundleCategory = routeArguments['bundle-category'];
+ if (!bundleCategory || !bundleListingDatas) {
+ return;
+ }
+
+ let bundleListingData: ?BundleListingData = null;
+ // Open the information page of a the bundle.
+ if (bundleCategory) | newIDE/app/src/MainFrame/StandAloneDialog.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Create a standalone page that can be used for bundles | 7,861 | 4ian/GDevelop | 10,154 | JavaScript | ClementPasteau | |
gridOffsetX: number,
gridOffsetY: number,
gridColor: number,
gridAlpha: number,
/** Is snap to grid activated? */
snap: boolean,
/** The zoom of the editor, 1 by default. */
zoomFactor: number,
/** Is the window mask shown? */
windowMask: boolean,
/** The name of the layer selected to place instances on. */
selectedLayer: string,
|};
export const getRecommendedInitialZoomFactor = (
largestSizeInPixels: number
) => {
// 700 is an empirical value obtained multiplying the largest size (1920) with
// the zoom factor (0.36) so that the screen black rectangle fits nicely on the canvas
// with only the left and right side panels opened on a Macbook screen.
return 700 / largestSizeInPixels;
};
export const prepareInstancesEditorSettings = (
object: any,
projectLargestResolutionSizeInPixels: number
): InstancesEditorSettings => {
return {
grid: object.grid || false,
gridType: object.gridType || 'rectangular',
gridWidth: object.gridWidth || 32,
gridHeight: object.gridHeight || 32,
gridOffsetX: object.gridOffsetX || 0,
gridOffsetY: object.gridOffsetY || 0,
gridColor:
object.gridColor !== undefined
? object.gridColor
: rgbToHexNumber(158, 180, 255),
gridAlpha: object.gridAlpha !== undefined ? object.gridAlpha : 0.8,
snap: object.snap || false,
zoomFactor: Math.max(
object.zoomFactor ||
getRecommendedInitialZoomFactor(projectLargestResolutionSizeInPixels),
0.01
),
windowMask: object.windowMask || false,
selectedLayer: object.selectedLayer || '', | No issues found. | gridOffsetX: number,
gridOffsetY: number,
gridColor: number,
gridAlpha: number,
/** Is snap to grid activated? */
snap: boolean,
/** The zoom of the editor, 1 by default. */
zoomFactor: number,
/** Is the window mask shown? */
windowMask: boolean,
/** The name of the layer selected to place instances on. */
selectedLayer: string,
|};
export const getRecommendedInitialZoomFactor = (
largestSizeInPixels: number
) => {
// 700 is an empirical value obtained multiplying the largest size (1920) with
// the zoom factor (0.36) so that the screen black rectangle fits nicely on the canvas
// with only the left and right side panels opened on a Macbook screen.
return 700 / largestSizeInPixels;
};
export const prepareInstancesEditorSettings = (
object: any,
projectLargestResolutionSizeInPixels: number
): InstancesEditorSettings => {
return {
grid: object.grid || false,
gridType: object.gridType || 'rectangular',
gridWidth: object.gridWidth || 32,
gridHeight: object.gridHeight || 32,
gridOffsetX: object.gridOffsetX || 0,
gridOffsetY: object.gridOffsetY || 0,
gridColor:
object.gridColor !== undefined
? object.gridColor
: rgbToHexNumber(158, 180, 255),
gridAlpha: object.gridAlpha !== undefined ? object.gridAlpha : 0.8,
snap: object.snap || false,
zoomFactor: Math.max(
object.zoomFactor ||
getRecommendedInitialZoomFactor(projectLargestResolutionSizeInPixels),
0.01
),
windowMask: object.windowMask || false,
selectedLayer: object.selectedLayer || '', | @@ -20,6 +20,9 @@ export type InstancesEditorSettings = {|
/** Is the window mask shown? */
windowMask: boolean,
+
+ /** The name of the layer selected to place instances on. */
+ selectedLayer: string,
|};
export const getRecommendedInitialZoomFactor = (
@@ -54,6 +57,7 @@ export const prepareInstancesEditorSettings = (
0.01
),
windowMask: object.windowMask || false,
+ selectedLayer: object.selectedLayer || '',
};
};
| newIDE/app/src/InstancesEditor/InstancesEditorSettings.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | fix(instances-editor): persist selected layer across sessions | 7,879 | 4ian/GDevelop | 10,154 | JavaScript | Digvijay-x1 | |
isVisible(): boolean {
return !this.hidden;
}
/**
* Return true if the object is hidden.
* @return true if the object is hidden.
*/
isHidden(): boolean {
return this.hidden;
}
/**
* Set the width of the object, if applicable.
* @param width The new width in pixels.
*/
setWidth(width: float): void {}
/**
* Set the height of the object, if applicable.
* @param height The new height in pixels.
*/
setHeight(height: float): void {}
/**
* Return the width of the object.
* @return The width of the object
*/
getWidth(): float {
return 0;
}
/**
* Return the height of the object.
* @return The height of the object
*/
getHeight(): float {
return 0;
}
/**
* Return the X position of the object center, **relative to the object X position** (`getDrawableX`).
* Use `getCenterXInScene` to get the position of the center in the scene.
*
* @return the X position of the object center, relative to `getDrawableX()`.
*/
getCenterX(): float {
return this.getWidth() / 2;
}
/** | No issues found. | isVisible(): boolean {
return !this.hidden;
}
/**
* Return true if the object is hidden.
* @return true if the object is hidden.
*/
isHidden(): boolean {
return this.hidden;
}
/**
* Set the width of the object, if applicable.
* @param width The new width in pixels.
*/
setWidth(width: float): void {}
/**
* Set the height of the object, if applicable.
* @param height The new height in pixels.
*/
setHeight(height: float): void {}
/**
* Return the width of the object.
* @return The width of the object
*/
getWidth(): float {
return 0;
}
/**
* Return the height of the object.
* @return The height of the object
*/
getHeight(): float {
return 0;
}
/**
* Return the X position of the object center, **relative to the object X position** (`getDrawableX`).
* Use `getCenterXInScene` to get the position of the center in the scene.
*
* @return the X position of the object center, relative to `getDrawableX()`.
*/
getCenterX(): float {
return this.getWidth() / 2;
}
/** | @@ -842,6 +842,12 @@ namespace gdjs {
return this.getY();
}
+ /**
+ * Rotate the object towards another object position.
+ * @param x The target x position
+ * @param y The target y position
+ * @param speed The rotation speed. 0 for an immediate rotation to the target position.
+ */
rotateTowardPosition(x: float, y: float, speed: float): void {
this.rotateTowardAngle(
gdjs.toDegrees(
@@ -855,8 +861,24 @@ namespace gdjs {
}
/**
- * @param angle The targeted direction angle.
- * @param speed The rotation speed.
+ * Rotate the object towards another object position (aiming at the center of the object).
+ * @param target The target object
+ * @param speed The rotation speed. 0 for an immediate rotation to the target object.
+ */
+ rotateTowardObject(target: gdjs.RuntimeObject | null, speed: float): void {
+ if (target === null) {
+ return;
+ }
+ this.rotateTowardPosition(
+ target.getDrawableX() + target.getCenterX(),
+ target.getDrawableY() + target.getCenterY(),
+ speed
+ );
+ }
+
+ /**
+ * @param angle The targeted angle.
+ * @param speed The rotation speed. 0 for an immediate rotation to the target angle.
*/
rotateTowardAngle(angle: float, speed: float): void {
if (speed === 0) { | GDJS/Runtime/runtimeobject.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | Add "Pick Nearest" and "Rotate toward object" action | 7,883 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | |
);
const onOpenHistory = React.useCallback(() => {
setIsHistoryOpen(true);
}, []);
const onCloseHistory = React.useCallback(() => {
setIsHistoryOpen(false);
}, []);
const {
aiRequestStorage,
editorFunctionCallResultsStorage,
getAiSettings,
} = React.useContext(AiRequestContext);
const {
getEditorFunctionCallResults,
addEditorFunctionCallResults,
clearEditorFunctionCallResults,
} = editorFunctionCallResultsStorage;
const {
updateAiRequest,
refreshAiRequest,
isSendingAiRequest,
getLastSendError,
setSendingAiRequest,
setLastSendError,
} = aiRequestStorage;
const updateToolbar = React.useCallback(
() => {
if (setToolbar) {
setToolbar(
<Toolbar
onStartOrOpenChat={onStartOrOpenChat}
canStartNewChat={canStartNewChat}
onOpenHistory={onOpenHistory}
/>
);
}
},
[setToolbar, onStartOrOpenChat, canStartNewChat, onOpenHistory]
);
React.useEffect(updateToolbar, [updateToolbar]);
React.useImperativeHandle(ref, () => ({
getProject: noop,
updateToolbar,
forceUpdateEditor: noop,
onEventsBasedObjectChildrenEdited: noop, | No issues found. | );
const onOpenHistory = React.useCallback(() => {
setIsHistoryOpen(true);
}, []);
const onCloseHistory = React.useCallback(() => {
setIsHistoryOpen(false);
}, []);
const {
aiRequestStorage,
editorFunctionCallResultsStorage,
getAiSettings,
} = React.useContext(AiRequestContext);
const {
getEditorFunctionCallResults,
addEditorFunctionCallResults,
clearEditorFunctionCallResults,
} = editorFunctionCallResultsStorage;
const {
updateAiRequest,
refreshAiRequest,
isSendingAiRequest,
getLastSendError,
setSendingAiRequest,
setLastSendError,
} = aiRequestStorage;
const updateToolbar = React.useCallback(
() => {
if (setToolbar) {
setToolbar(
<Toolbar
onStartOrOpenChat={onStartOrOpenChat}
canStartNewChat={canStartNewChat}
onOpenHistory={onOpenHistory}
/>
);
}
},
[setToolbar, onStartOrOpenChat, canStartNewChat, onOpenHistory]
);
React.useEffect(updateToolbar, [updateToolbar]);
React.useImperativeHandle(ref, () => ({
getProject: noop,
updateToolbar,
forceUpdateEditor: noop,
onEventsBasedObjectChildrenEdited: noop, | @@ -692,7 +692,7 @@ export const AskAiEditor = React.memo<Props>(
fileMetadata,
storageProviderName,
mode,
- toolsVersion: 'v3',
+ toolsVersion: 'v4',
aiConfiguration: {
presetId: aiConfigurationPresetId,
}, | newIDE/app/src/AiGeneration/AskAiEditorContainer.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Adapt editor function to duplicate object | 7,889 | 4ian/GDevelop | 10,154 | JavaScript | ClementPasteau | |
},
[setSelectedAiRequestId]
);
const onOpenHistory = React.useCallback(() => {
setIsHistoryOpen(true);
}, []);
const onCloseHistory = React.useCallback(() => {
setIsHistoryOpen(false);
}, []);
const {
aiRequestStorage,
editorFunctionCallResultsStorage,
getAiSettings,
} = React.useContext(AiRequestContext);
const {
getEditorFunctionCallResults,
addEditorFunctionCallResults,
clearEditorFunctionCallResults,
} = editorFunctionCallResultsStorage;
const {
updateAiRequest,
refreshAiRequest,
isSendingAiRequest,
getLastSendError,
setSendingAiRequest,
setLastSendError,
} = aiRequestStorage;
const updateToolbar = React.useCallback(
() => {
if (setToolbar) {
setToolbar(
<Toolbar
onStartOrOpenChat={onStartOrOpenChat}
canStartNewChat={canStartNewChat}
onOpenHistory={onOpenHistory}
/>
);
}
},
[setToolbar, onStartOrOpenChat, canStartNewChat, onOpenHistory]
);
React.useEffect(updateToolbar, [updateToolbar]);
React.useImperativeHandle(ref, () => ({
getProject: noop,
updateToolbar, | No issues found. | },
[setSelectedAiRequestId]
);
const onOpenHistory = React.useCallback(() => {
setIsHistoryOpen(true);
}, []);
const onCloseHistory = React.useCallback(() => {
setIsHistoryOpen(false);
}, []);
const {
aiRequestStorage,
editorFunctionCallResultsStorage,
getAiSettings,
} = React.useContext(AiRequestContext);
const {
getEditorFunctionCallResults,
addEditorFunctionCallResults,
clearEditorFunctionCallResults,
} = editorFunctionCallResultsStorage;
const {
updateAiRequest,
refreshAiRequest,
isSendingAiRequest,
getLastSendError,
setSendingAiRequest,
setLastSendError,
} = aiRequestStorage;
const updateToolbar = React.useCallback(
() => {
if (setToolbar) {
setToolbar(
<Toolbar
onStartOrOpenChat={onStartOrOpenChat}
canStartNewChat={canStartNewChat}
onOpenHistory={onOpenHistory}
/>
);
}
},
[setToolbar, onStartOrOpenChat, canStartNewChat, onOpenHistory]
);
React.useEffect(updateToolbar, [updateToolbar]);
React.useImperativeHandle(ref, () => ({
getProject: noop,
updateToolbar, | @@ -6,6 +6,8 @@ import {
type RenderEditorContainerPropsWithRef,
type SceneEventsOutsideEditorChanges,
type InstancesOutsideEditorChanges,
+ type ObjectsOutsideEditorChanges,
+ type ObjectGroupsOutsideEditorChanges,
} from '../MainFrame/EditorContainers/BaseEditor';
import { type ObjectWithContext } from '../ObjectsList/EnumerateObjects';
import Paper from '../UI/Paper';
@@ -63,6 +65,8 @@ import { SubscriptionSuggestionContext } from '../Profile/Subscription/Subscript
const gd: libGDevelop = global.gd;
+const AI_TOOLS_VERSION = 'v5';
+
const useProcessFunctionCalls = ({
i18n,
project,
@@ -74,6 +78,8 @@ const useProcessFunctionCalls = ({
addEditorFunctionCallResults,
onSceneEventsModifiedOutsideEditor,
onInstancesModifiedOutsideEditor,
+ onObjectsModifiedOutsideEditor,
+ onObjectGroupsModifiedOutsideEditor,
onExtensionInstalled,
}: {|
i18n: I18nType,
@@ -95,6 +101,12 @@ const useProcessFunctionCalls = ({
onInstancesModifiedOutsideEditor: (
changes: InstancesOutsideEditorChanges
) => void,
+ onObjectsModifiedOutsideEditor: (
+ changes: ObjectsOutsideEditorChanges
+ ) => void,
+ onObjectGroupsModifiedOutsideEditor: (
+ changes: ObjectGroupsOutsideEditorChanges
+ ) => void,
onExtensionInstalled: (extensionNames: Array<string>) => void,
|}) => {
const { ensureExtensionInstalled } = useEnsureExtensionInstalled({
@@ -170,6 +182,8 @@ const useProcessFunctionCalls = ({
},
onSceneEventsModifiedOutsideEditor,
onInstancesModifiedOutsideEditor,
+ onObjectsModifiedOutsideEditor,
+ onObjectGroupsModifiedOutsideEditor,
ensureExtensionInstalled,
searchAndInstallAsset,
});
@@ -191,6 +205,8 @@ const useProcessFunctionCalls = ({
generateEvents,
onSceneEventsModifiedOutsideEditor,
onInstancesModifiedOutsideEditor,
+ onObjectsModifiedOutsideEditor,
+ onObjectGroupsModifiedOutsideEditor,
triggerSendEditorFunctionCal | newIDE/app/src/AiGeneration/AskAiEditorContainer.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | New Editor function to update scene groups | 7,910 | 4ian/GDevelop | 10,154 | JavaScript | ClementPasteau | |
pixiContainer: PIXI.Container,
pixiResourcesLoader: Class<PixiResourcesLoader>
) {
super(
project,
instance,
//$FlowFixMe It's ok because RenderedUnknownInstance don't use it.
associatedObjectConfiguration,
pixiContainer,
pixiResourcesLoader
);
//This renderer show a placeholder for the object:
this._pixiObject = new PIXI.Sprite(
this._pixiResourcesLoader.getInvalidPIXITexture()
);
this._pixiContainer.addChild(this._pixiObject);
}
onRemovedFromScene(): void {
super.onRemovedFromScene();
this._pixiObject.destroy();
}
static getThumbnail(
project: gdProject,
resourcesLoader: Class<ResourcesLoader>,
objectConfiguration: gdObjectConfiguration
) {
return 'res/unknown32.png';
}
update() {
// Avoid to use _pixiObject after destroy is called.
// It can happen when onRemovedFromScene and update cross each other.
if (!this._pixiObject) {
return;
}
const objectTextureFrame = this._pixiObject.texture.frame;
// In case the texture is not loaded yet, we don't want to crash.
if (!objectTextureFrame) return;
this._pixiObject.anchor.x = 0.5;
this._pixiObject.anchor.y = 0.5;
this._pixiObject.rotation = RenderedInstance.toRad(
this._instance.getAngle()
);
this._pixiObject.scale.x = this.getWidth() / objectTextureFrame.width;
this._pixiObject.scale.y = this.getHeight() / objectTextureFrame.height;
this._pixiObject.position.x = this._instance.getX() + this.getCenterX();
this._pixiObject.position.y = this._instance.getY() + this.getCenterY(); | No issues found. | pixiContainer: PIXI.Container,
pixiResourcesLoader: Class<PixiResourcesLoader>
) {
super(
project,
instance,
//$FlowFixMe It's ok because RenderedUnknownInstance don't use it.
associatedObjectConfiguration,
pixiContainer,
pixiResourcesLoader
);
//This renderer show a placeholder for the object:
this._pixiObject = new PIXI.Sprite(
this._pixiResourcesLoader.getInvalidPIXITexture()
);
this._pixiContainer.addChild(this._pixiObject);
}
onRemovedFromScene(): void {
super.onRemovedFromScene();
this._pixiObject.destroy();
}
static getThumbnail(
project: gdProject,
resourcesLoader: Class<ResourcesLoader>,
objectConfiguration: gdObjectConfiguration
) {
return 'res/unknown32.png';
}
update() {
// Avoid to use _pixiObject after destroy is called.
// It can happen when onRemovedFromScene and update cross each other.
if (!this._pixiObject) {
return;
}
const objectTextureFrame = this._pixiObject.texture.frame;
// In case the texture is not loaded yet, we don't want to crash.
if (!objectTextureFrame) return;
this._pixiObject.anchor.x = 0.5;
this._pixiObject.anchor.y = 0.5;
this._pixiObject.rotation = RenderedInstance.toRad(
this._instance.getAngle()
);
this._pixiObject.scale.x = this.getWidth() / objectTextureFrame.width;
this._pixiObject.scale.y = this.getHeight() / objectTextureFrame.height;
this._pixiObject.position.x = this._instance.getX() + this.getCenterX();
this._pixiObject.position.y = this._instance.getY() + this.getCenterY(); | @@ -11,20 +11,23 @@ export default class RenderedUnknownInstance extends RenderedInstance {
constructor(
project: gdProject,
instance: gdInitialInstance,
- associatedObjectConfiguration: gdObjectConfiguration,
+ associatedObjectConfiguration: gdObjectConfiguration | null,
pixiContainer: PIXI.Container,
pixiResourcesLoader: Class<PixiResourcesLoader>
) {
super(
project,
instance,
+ //$FlowFixMe It's ok because RenderedUnknownInstance don't use it.
associatedObjectConfiguration,
pixiContainer,
pixiResourcesLoader
);
//This renderer show a placeholder for the object:
- this._pixiObject = new PIXI.Graphics();
+ this._pixiObject = new PIXI.Sprite(
+ this._pixiResourcesLoader.getInvalidPIXITexture()
+ );
this._pixiContainer.addChild(this._pixiObject);
}
@@ -42,21 +45,34 @@ export default class RenderedUnknownInstance extends RenderedInstance {
}
update() {
- const width = this.getWidth();
- const height = this.getHeight();
-
- this._pixiObject.clear();
- this._pixiObject.beginFill(0x0033ff);
- this._pixiObject.lineStyle(1, 0xffd900, 1);
- this._pixiObject.moveTo(-width / 2, -height / 2);
- this._pixiObject.lineTo(width / 2, -height / 2);
- this._pixiObject.lineTo(width / 2, height / 2);
- this._pixiObject.lineTo(-width / 2, height / 2);
- this._pixiObject.lineTo(-width / 2, -height / 2);
- this._pixiObject.endFill();
-
- this._pixiObject.position.x = this._instance.getX() + width / 2;
- this._pixiObject.position.y = this._instance.getY() + height / 2;
- this._pixiObject.angle = this._instance.getAngle();
+ // Avoid to use _pixiObject after destroy is called.
+ // It can happen when onRemovedFromScene and update cross each other.
+ if (!this._pixiObject) {
+ return;
+ }
+ const objectTextureFrame = this._pixiObject.texture.frame;
+ // In case the texture is not loaded yet, we don't want to | newIDE/app/src/ObjectsRendering/Renderers/RenderedUnknownInstance.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Display a placeholder for instances with unknown objects in the editor | 7,933 | 4ian/GDevelop | 10,154 | JavaScript | D8H | |
project: ?gdProject,
resourceManagementProps: ResourceManagementProps,
onExtensionInstalled: (extensionNames: Array<string>) => void,
|}) => {
const { profile, getAuthorizationHeader } = React.useContext(
AuthenticatedUserContext
);
const installAsset = useInstallAsset({
project,
resourceManagementProps,
onExtensionInstalled,
});
return {
searchAndInstallAsset: React.useCallback(
async ({
objectsContainer,
objectName,
...assetSearchOptions
}: AssetSearchAndInstallOptions): Promise<AssetSearchAndInstallResult> => {
if (!profile) throw new Error('User should be authenticated.');
const assetSearch: AssetSearch = await retryIfFailed({ times: 2 }, () =>
createAssetSearch(getAuthorizationHeader, {
userId: profile.id,
...assetSearchOptions,
})
);
if (!assetSearch.results || assetSearch.results.length === 0) {
return {
status: 'nothing-found',
message: 'No assets found.',
createdObjects: [],
assetShortHeader: null,
};
}
// In the future, we could ask the user to select the asset they want to use.
// For now, we just return the first asset.
const chosenResult = assetSearch.results[0];
if (!chosenResult) throw new Error('No asset found.');
const assetShortHeader = chosenResult.asset;
const installOutput = await installAsset({
assetShortHeader,
objectsContainer,
requestedObjectName: objectName,
});
if (!installOutput) {
return { | No issues found. | project: ?gdProject,
resourceManagementProps: ResourceManagementProps,
onExtensionInstalled: (extensionNames: Array<string>) => void,
|}) => {
const { profile, getAuthorizationHeader } = React.useContext(
AuthenticatedUserContext
);
const installAsset = useInstallAsset({
project,
resourceManagementProps,
onExtensionInstalled,
});
return {
searchAndInstallAsset: React.useCallback(
async ({
objectsContainer,
objectName,
...assetSearchOptions
}: AssetSearchAndInstallOptions): Promise<AssetSearchAndInstallResult> => {
if (!profile) throw new Error('User should be authenticated.');
const assetSearch: AssetSearch = await retryIfFailed({ times: 2 }, () =>
createAssetSearch(getAuthorizationHeader, {
userId: profile.id,
...assetSearchOptions,
})
);
if (!assetSearch.results || assetSearch.results.length === 0) {
return {
status: 'nothing-found',
message: 'No assets found.',
createdObjects: [],
assetShortHeader: null,
};
}
// In the future, we could ask the user to select the asset they want to use.
// For now, we just return the first asset.
const chosenResult = assetSearch.results[0];
if (!chosenResult) throw new Error('No asset found.');
const assetShortHeader = chosenResult.asset;
const installOutput = await installAsset({
assetShortHeader,
objectsContainer,
requestedObjectName: objectName,
});
if (!installOutput) {
return { | @@ -34,7 +34,7 @@ export const useSearchAndInstallAsset = ({
return {
searchAndInstallAsset: React.useCallback(
async ({
- scene,
+ objectsContainer,
objectName,
...assetSearchOptions
}: AssetSearchAndInstallOptions): Promise<AssetSearchAndInstallResult> => {
@@ -63,7 +63,7 @@ export const useSearchAndInstallAsset = ({
const installOutput = await installAsset({
assetShortHeader,
- objectsContainer: scene.getObjects(),
+ objectsContainer,
requestedObjectName: objectName,
});
| newIDE/app/src/AiGeneration/UseSearchAndInstallAsset.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Object Editor Functions handle global scope | 7,959 | 4ian/GDevelop | 10,154 | JavaScript | ClementPasteau | |
// TODO Remove the ternary when all parameter declarations use
// 'number' instead of 'expression'.
const parameterType: string =
parameterMetadata.getType() === 'expression'
? 'number'
: parameterMetadata.getType();
let expressionIsValid = true;
if (!shouldNotBeValidated({ value, parameterType })) {
expressionIsValid = gd.InstructionValidator.isParameterValid(
platform,
projectScopedContainers,
instruction,
metadata,
parameterIndex,
value
);
// TODO Move this code inside `InstructionValidator.isParameterValid`
if (
expressionIsValid &&
parameterType === 'functionParameterName'
) {
const eventsFunction = props.scope.eventsFunction;
if (eventsFunction) {
const eventsBasedEntity =
props.scope.eventsBasedBehavior ||
props.scope.eventsBasedObject;
const functionsContainer = eventsBasedEntity
? eventsBasedEntity.getEventsFunctions()
: props.scope.eventsFunctionsExtension
? props.scope.eventsFunctionsExtension.getEventsFunctions()
: null;
if (functionsContainer) {
const allowedParameterTypes = parameterMetadata
.getExtraInfo()
.split(',');
const parameters = enumerateParametersUsableInExpressions(
functionsContainer,
eventsFunction,
allowedParameterTypes
);
const functionParameterNameExpression = instruction
.getParameter(parameterIndex)
.getPlainString();
const functionParameterName = functionParameterNameExpression.substring(
1,
functionParameterNameExpression.length - 1
);
expressionIsValid = parameters.some(
parameter => parameter.getName() === functionParameterName
); | No issues found. | // TODO Remove the ternary when all parameter declarations use
// 'number' instead of 'expression'.
const parameterType: string =
parameterMetadata.getType() === 'expression'
? 'number'
: parameterMetadata.getType();
let expressionIsValid = true;
if (!shouldNotBeValidated({ value, parameterType })) {
expressionIsValid = gd.InstructionValidator.isParameterValid(
platform,
projectScopedContainers,
instruction,
metadata,
parameterIndex,
value
);
// TODO Move this code inside `InstructionValidator.isParameterValid`
if (
expressionIsValid &&
parameterType === 'functionParameterName'
) {
const eventsFunction = props.scope.eventsFunction;
if (eventsFunction) {
const eventsBasedEntity =
props.scope.eventsBasedBehavior ||
props.scope.eventsBasedObject;
const functionsContainer = eventsBasedEntity
? eventsBasedEntity.getEventsFunctions()
: props.scope.eventsFunctionsExtension
? props.scope.eventsFunctionsExtension.getEventsFunctions()
: null;
if (functionsContainer) {
const allowedParameterTypes = parameterMetadata
.getExtraInfo()
.split(',');
const parameters = enumerateParametersUsableInExpressions(
functionsContainer,
eventsFunction,
allowedParameterTypes
);
const functionParameterNameExpression = instruction
.getParameter(parameterIndex)
.getPlainString();
const functionParameterName = functionParameterNameExpression.substring(
1,
functionParameterNameExpression.length - 1
);
expressionIsValid = parameters.some(
parameter => parameter.getName() === functionParameterName
); | @@ -45,10 +45,7 @@ import {
import { enumerateParametersUsableInExpressions } from '../ParameterFields/EnumerateFunctionParameters';
import { getFunctionNameFromType } from '../../EventsFunctionsExtensionsLoader';
import { ExtensionStoreContext } from '../../AssetStore/ExtensionStore/ExtensionStoreContext';
-import { getAllRequiredBehaviorTypes } from '../ParameterFields/ObjectField';
-import { checkHasRequiredBehaviors } from '../../ObjectsList/ObjectSelector';
import Warning from '../../UI/CustomSvgIcons/Warning';
-import { getRootVariableName } from '../../EventsSheet/ParameterFields/VariableField';
const gd: libGDevelop = global.gd;
@@ -286,88 +283,23 @@ const Instruction = (props: Props) => {
}
const parameterMetadata = metadata.getParameter(parameterIndex);
- // TODO Remove the ternary when any parameter declaration uses
+ // TODO Remove the ternary when all parameter declarations use
// 'number' instead of 'expression'.
const parameterType: string =
parameterMetadata.getType() === 'expression'
? 'number'
: parameterMetadata.getType();
let expressionIsValid = true;
if (!shouldNotBeValidated({ value, parameterType })) {
- if (
- gd.ParameterMetadata.isExpression('number', parameterType) ||
- gd.ParameterMetadata.isExpression('string', parameterType) ||
- gd.ParameterMetadata.isExpression('variable', parameterType)
- ) {
- const expressionNode = instruction
- .getParameter(parameterIndex)
- .getRootNode();
- const expressionValidator = new gd.ExpressionValidator(
- gd.JsPlatform.get(),
- projectScopedContainers,
- parameterType,
- parameterMetadata.getExtraInfo()
- );
- expressionNode.visit(expressionValidator);
- | newIDE/app/src/EventsSheet/EventsTree/Instruction.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Show object parameters in red if any behavior parameter is wrongly filled | 7,997 | 4ian/GDevelop | 10,154 | JavaScript | D8H | |
);
const duplicateAndEditVariant = React.useCallback(
(i18n: I18nType, newName: string) => {
duplicateVariant(
newName,
customObjectConfiguration,
customObjectEventsBasedObject,
customObjectExtension,
project,
i18n
);
setDuplicateAndEditVariantDialogOpen(false);
forceUpdate();
editVariant();
},
[
customObjectConfiguration,
customObjectEventsBasedObject,
customObjectExtension,
forceUpdate,
project,
editVariant,
]
);
const doDeleteVariant = React.useCallback(
async () => {
const hasConfirmedDeletion = await showDeleteConfirmation({
title: t`Remove variant`,
message: t`Are you sure you want to remove this variant from your project? This can't be undone.`,
});
if (!hasConfirmedDeletion) {
return;
}
deleteVariant(
customObjectConfiguration,
customObjectEventsBasedObject,
customObjectExtension,
project,
onDeleteEventsBasedObjectVariant
);
forceUpdate();
},
[
customObjectConfiguration,
customObjectEventsBasedObject,
forceUpdate,
onDeleteEventsBasedObjectVariant,
project,
customObjectExtension, | No issues found. | );
const duplicateAndEditVariant = React.useCallback(
(i18n: I18nType, newName: string) => {
duplicateVariant(
newName,
customObjectConfiguration,
customObjectEventsBasedObject,
customObjectExtension,
project,
i18n
);
setDuplicateAndEditVariantDialogOpen(false);
forceUpdate();
editVariant();
},
[
customObjectConfiguration,
customObjectEventsBasedObject,
customObjectExtension,
forceUpdate,
project,
editVariant,
]
);
const doDeleteVariant = React.useCallback(
async () => {
const hasConfirmedDeletion = await showDeleteConfirmation({
title: t`Remove variant`,
message: t`Are you sure you want to remove this variant from your project? This can't be undone.`,
});
if (!hasConfirmedDeletion) {
return;
}
deleteVariant(
customObjectConfiguration,
customObjectEventsBasedObject,
customObjectExtension,
project,
onDeleteEventsBasedObjectVariant
);
forceUpdate();
},
[
customObjectConfiguration,
customObjectEventsBasedObject,
forceUpdate,
onDeleteEventsBasedObjectVariant,
project,
customObjectExtension, | @@ -25,7 +25,9 @@ import { type ResourceManagementProps } from '../../ResourcesList/ResourceSource
import Paper from '../../UI/Paper';
import { ColumnStackLayout, LineStackLayout } from '../../UI/Layout';
import { IconContainer } from '../../UI/IconContainer';
-import Remove from '../../UI/CustomSvgIcons/Remove';
+import RemoveIcon from '../../UI/CustomSvgIcons/Remove';
+import VisibilityIcon from '../../UI/CustomSvgIcons/Visibility';
+import VisibilityOffIcon from '../../UI/CustomSvgIcons/VisibilityOff';
import useForceUpdate, { useForceRecompute } from '../../Utils/UseForceUpdate';
import ChevronArrowTop from '../../UI/CustomSvgIcons/ChevronArrowTop';
import ChevronArrowRight from '../../UI/CustomSvgIcons/ChevronArrowRight';
@@ -98,22 +100,27 @@ const objectVariablesHelpLink = getHelpLink(
'/all-features/variables/object-variables'
);
+type TitleBarButton = {|
+ id: string,
+ icon: any,
+ label?: MessageDescriptor,
+ onClick?: () => void,
+|};
+
const CollapsibleSubPanel = ({
renderContent,
isFolded,
toggleFolded,
title,
titleIcon,
- onRemove,
- removeLabel,
+ titleBarButtons,
}: {|
renderContent: () => React.Node,
isFolded: boolean,
toggleFolded: () => void,
titleIcon?: ?React.Node,
title: string,
- onRemove?: () => void,
- removeLabel?: MessageDescriptor,
+ titleBarButtons?: Array<TitleBarButton>,
|}) => (
<Paper background="medium">
<Line expand>
@@ -134,15 +141,24 @@ const CollapsibleSubPanel = ({
{title}
</Text>
</Line>
-
- {onRemove ? (
- <Line noMargin>
- <IconButton tooltip={removeLabel} onClick={onRemove} size="small">
- <Remove style={styles.icon} />
- </IconButton>
- <Spacer />
- </Line>
- ) : null}
+ <Line noMargin>
+ {titleBarButtons &&
+ titleBarButtons.map(button => {
+ const Icon = button.icon;
+ | newIDE/app/src/ObjectEditor/CompactObjectPropertiesEditor/index.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Allow to set effects as initially disabled | 8,002 | 4ian/GDevelop | 10,154 | JavaScript | D8H | |
extensionShortHeader
)
) {
// Allow to reinstall the extension even if the versions match.
requiredExtensionInstallation.missingExtensionShortHeaders.push(
extensionShortHeader
);
}
const wasExtensionInstalled = await installExtension({
project,
requiredExtensionInstallation,
userSelectedExtensionNames: [extensionShortHeader.name],
importedSerializedExtensions: [],
onWillInstallExtension,
onExtensionInstalled,
updateMode: 'all',
reason: 'extension',
});
if (!wasExtensionInstalled) {
return false;
}
createBadgeFirstExtension();
setExtensionWasInstalled(true);
} catch (rawError) {
showErrorBox({
message: i18n._(
t`Unable to download and install the extension and its dependencies. Verify that your internet connection is working or try again later.`
),
rawError,
errorId: 'download-extension-error',
});
return false;
}
} else {
const installedOrImportedExtensionNames = await importExtension({
i18n,
project,
onWillInstallExtension,
onExtensionInstalled,
});
if (installedOrImportedExtensionNames.length > 0) {
setExtensionWasInstalled(true);
onExtensionInstalled(installedOrImportedExtensionNames);
return true;
}
}
return false;
} finally {
setIsInstalling(false);
}
}; | No issues found. | extensionShortHeader
)
) {
// Allow to reinstall the extension even if the versions match.
requiredExtensionInstallation.missingExtensionShortHeaders.push(
extensionShortHeader
);
}
const wasExtensionInstalled = await installExtension({
project,
requiredExtensionInstallation,
userSelectedExtensionNames: [extensionShortHeader.name],
importedSerializedExtensions: [],
onWillInstallExtension,
onExtensionInstalled,
updateMode: 'all',
reason: 'extension',
});
if (!wasExtensionInstalled) {
return false;
}
createBadgeFirstExtension();
setExtensionWasInstalled(true);
} catch (rawError) {
showErrorBox({
message: i18n._(
t`Unable to download and install the extension and its dependencies. Verify that your internet connection is working or try again later.`
),
rawError,
errorId: 'download-extension-error',
});
return false;
}
} else {
const installedOrImportedExtensionNames = await importExtension({
i18n,
project,
onWillInstallExtension,
onExtensionInstalled,
});
if (installedOrImportedExtensionNames.length > 0) {
setExtensionWasInstalled(true);
onExtensionInstalled(installedOrImportedExtensionNames);
return true;
}
}
return false;
} finally {
setIsInstalling(false);
}
}; | @@ -93,6 +93,16 @@ const ExtensionsSearchDialog = ({
extensionShortHeadersByName,
}
);
+ if (
+ !requiredExtensionInstallation.missingExtensionShortHeaders.includes(
+ extensionShortHeader
+ )
+ ) {
+ // Allow to reinstall the extension even if the versions match.
+ requiredExtensionInstallation.missingExtensionShortHeaders.push(
+ extensionShortHeader
+ );
+ }
const wasExtensionInstalled = await installExtension({
project,
requiredExtensionInstallation, | newIDE/app/src/AssetStore/ExtensionStore/ExtensionsSearchDialog.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Fix extension reinstall wasn't doing anything | 8,017 | 4ian/GDevelop | 10,154 | JavaScript | D8H | |
}: Props) => {
const [
shouldShowDeprecatedProperties,
setShouldShowDeprecatedProperties,
] = React.useState<boolean>(false);
const basicPropertiesSchema = React.useMemo(
() =>
propertiesMapToSchema(
propertiesValues,
behavior => behavior.getProperties(),
(behavior, name, value) => {
behavior.updateProperty(name, value);
},
object,
'Basic'
),
[propertiesValues, object]
);
const areAdvancedPropertiesExpandedByDefault = React.useMemo(
() =>
areAdvancedPropertiesModified(propertiesValues, getPropertyDefaultValue),
[getPropertyDefaultValue, propertiesValues]
);
const advancedPropertiesSchema = React.useMemo<Schema>(
() =>
propertiesMapToSchema(
propertiesValues,
behavior => behavior.getProperties(),
(behavior, name, value) => {
behavior.updateProperty(name, value);
},
object,
'Advanced'
),
[propertiesValues, object]
);
const deprecatedPropertiesSchema = React.useMemo<Schema>(
() =>
propertiesMapToSchema(
propertiesValues,
behavior => behavior.getProperties(),
(behavior, name, value) => {
behavior.updateProperty(name, value);
},
object,
'Deprecated'
), | No issues found. | }: Props) => {
const [
shouldShowDeprecatedProperties,
setShouldShowDeprecatedProperties,
] = React.useState<boolean>(false);
const basicPropertiesSchema = React.useMemo(
() =>
propertiesMapToSchema(
propertiesValues,
behavior => behavior.getProperties(),
(behavior, name, value) => {
behavior.updateProperty(name, value);
},
object,
'Basic'
),
[propertiesValues, object]
);
const areAdvancedPropertiesExpandedByDefault = React.useMemo(
() =>
areAdvancedPropertiesModified(propertiesValues, getPropertyDefaultValue),
[getPropertyDefaultValue, propertiesValues]
);
const advancedPropertiesSchema = React.useMemo<Schema>(
() =>
propertiesMapToSchema(
propertiesValues,
behavior => behavior.getProperties(),
(behavior, name, value) => {
behavior.updateProperty(name, value);
},
object,
'Advanced'
),
[propertiesValues, object]
);
const deprecatedPropertiesSchema = React.useMemo<Schema>(
() =>
propertiesMapToSchema(
propertiesValues,
behavior => behavior.getProperties(),
(behavior, name, value) => {
behavior.updateProperty(name, value);
},
object,
'Deprecated'
), | @@ -0,0 +1,220 @@
+// @flow
+import { Trans } from '@lingui/macro';
+
+import * as React from 'react';
+import PropertiesEditor, {
+ type Schema,
+ type Instances,
+} from '../PropertiesEditor';
+import propertiesMapToSchema from '../PropertiesEditor/PropertiesMapToSchema';
+import EmptyMessage from '../UI/EmptyMessage';
+import { Column, Line } from '../UI/Grid';
+import FlatButton from '../UI/FlatButton';
+import Text from '../UI/Text';
+import { Accordion, AccordionHeader, AccordionBody } from '../UI/Accordion';
+import { mapFor } from '../Utils/MapFor';
+import { type ResourceManagementProps } from '../ResourcesList/ResourceSource';
+import { ColumnStackLayout } from '../UI/Layout';
+import { type UnsavedChanges } from '../MainFrame/UnsavedChangesContext';
+import { ProjectScopedContainersAccessor } from '../InstructionOrExpression/EventsScope';
+
+export const areAdvancedPropertiesModified = (
+ propertiesValues: gdMapStringPropertyDescriptor,
+ getPropertyDefaultValue: (propertyName: string) => string
+) => {
+ const propertyNames = propertiesValues.keys();
+ let hasFoundModifiedAdvancedProperty = false;
+ mapFor(0, propertyNames.size(), i => {
+ const name = propertyNames.at(i);
+ const property = propertiesValues.get(name);
+ const currentValue = property.getValue();
+ const defaultValue = getPropertyDefaultValue(name);
+
+ // Some boolean properties can be set to an empty string to mean false.
+ const hasDefaultValue =
+ property.getType().toLowerCase() === 'boolean'
+ ? (currentValue === 'true') === (defaultValue === 'true')
+ : currentValue === defaultValue;
+ if (property.isAdvanced() && !hasDefaultValue) {
+ hasFoundModifiedAdvancedProperty = true;
+ }
+ });
+ return hasFoundModifiedAdvancedProperty;
+};
+
+const hasSchemaAnyProperty = (propertiesSchema: Schema) =>
+ !propertiesSchema.every(
+ property =>
+ property.isHiddenWhenOnlyOneChoice &&
+ property.getChoices &&
+ propert | newIDE/app/src/PropertiesEditor/PropertiesEditorByVisibility.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Collapse advanced properties in the object editor | 8,028 | 4ian/GDevelop | 10,154 | JavaScript | D8H | |
if (!remote) return;
return remote.getCurrentWindow().on('focus', cb);
}
static onBlur(cb: () => void) {
if (!remote) return;
return remote.getCurrentWindow().on('blur', cb);
}
static onClose(cb: () => void) {
if (!remote) return;
return remote.getCurrentWindow().on('close', cb);
}
/**
* Return the arguments passed to the IDE, either from Electron
* or from the web-app URL. The resulting object will have a key "_"
* containing an array of string, representing all the arguments that
* didn't have an option associated with them (see https://github.com/substack/minimist).
* (On the web-app, this is emulated using the "project" argument).
*/
static getArguments(): AppArguments {
if (remote) {
return remote.getGlobal('args');
}
const argumentsObject = {};
const params = new URLSearchParams(window.location.search);
params.forEach((value, name) => (argumentsObject[name] = value));
// Emulate the minimist behavior of putting the positional arguments
// in "_".
argumentsObject[POSITIONAL_ARGUMENTS_KEY] = argumentsObject.project
? [argumentsObject.project]
: [];
return argumentsObject;
}
/**
* On web, removes a list of query params from the URL.
*/
static removeArguments(argumentNames: string[]) {
// On Electron, we don't have a way to modify global args.
if (remote) return;
const url = new URL(window.location.href);
for (const argumentName of argumentNames) { | No issues found. | if (!remote) return;
return remote.getCurrentWindow().on('focus', cb);
}
static onBlur(cb: () => void) {
if (!remote) return;
return remote.getCurrentWindow().on('blur', cb);
}
static onClose(cb: () => void) {
if (!remote) return;
return remote.getCurrentWindow().on('close', cb);
}
/**
* Return the arguments passed to the IDE, either from Electron
* or from the web-app URL. The resulting object will have a key "_"
* containing an array of string, representing all the arguments that
* didn't have an option associated with them (see https://github.com/substack/minimist).
* (On the web-app, this is emulated using the "project" argument).
*/
static getArguments(): AppArguments {
if (remote) {
return remote.getGlobal('args');
}
const argumentsObject = {};
const params = new URLSearchParams(window.location.search);
params.forEach((value, name) => (argumentsObject[name] = value));
// Emulate the minimist behavior of putting the positional arguments
// in "_".
argumentsObject[POSITIONAL_ARGUMENTS_KEY] = argumentsObject.project
? [argumentsObject.project]
: [];
return argumentsObject;
}
/**
* On web, removes a list of query params from the URL.
*/
static removeArguments(argumentNames: string[]) {
// On Electron, we don't have a way to modify global args.
if (remote) return;
const url = new URL(window.location.href);
for (const argumentName of argumentNames) { | @@ -406,4 +406,10 @@ export default class Window {
const browserWindow = remote.getCurrentWindow();
return browserWindow.isFullScreen();
}
+
+ static toggleMaximize() {
+ if (!ipcRenderer) return;
+
+ ipcRenderer.invoke('window-maximize-toggle');
+ }
} | newIDE/app/src/Utils/Window.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | feat: Add "window-maximize-toggle" for macOS | 8,053 | 4ian/GDevelop | 10,154 | JavaScript | ViktorVovk | |
(await onProgress(loadedCount, sceneState.resourceNames.length));
}
);
sceneState.status = 'loaded';
}
private async _loadResource(resource: ResourceData): Promise<void> {
const resourceManager = this._resourceManagersMap.get(resource.kind);
if (!resourceManager) {
logger.warn(
'Unknown resource kind: "' +
resource.kind +
'" for: "' +
resource.name +
'".'
);
return;
}
await resourceManager.loadResource(resource.name);
}
/**
* Load and process a scene that is needed right away.
*
* The renderer will show a loading screen while its done.
*/
async loadAndProcessSceneResources(
sceneName: string,
onProgress?: (count: number, total: number) => Promise<void>
): Promise<void> {
if (this.areSceneAssetsReady(sceneName)) {
return;
}
await this.loadSceneResources(sceneName, onProgress);
const sceneState = this._sceneLoadingStates.get(sceneName);
if (!sceneState) {
logger.warn(
'Can\'t load resource for unknown scene: "' + sceneName + '".'
);
return;
}
let parsedCount = 0;
for (const resourceName of sceneState.resourceNames) {
const resource = this._resources.get(resourceName);
if (!resource) {
logger.warn('Unable to find resource "' + resourceName + '".');
continue;
}
await this._processResource(resource); | No issues found. | (await onProgress(loadedCount, sceneState.resourceNames.length));
}
);
sceneState.status = 'loaded';
}
private async _loadResource(resource: ResourceData): Promise<void> {
const resourceManager = this._resourceManagersMap.get(resource.kind);
if (!resourceManager) {
logger.warn(
'Unknown resource kind: "' +
resource.kind +
'" for: "' +
resource.name +
'".'
);
return;
}
await resourceManager.loadResource(resource.name);
}
/**
* Load and process a scene that is needed right away.
*
* The renderer will show a loading screen while its done.
*/
async loadAndProcessSceneResources(
sceneName: string,
onProgress?: (count: number, total: number) => Promise<void>
): Promise<void> {
if (this.areSceneAssetsReady(sceneName)) {
return;
}
await this.loadSceneResources(sceneName, onProgress);
const sceneState = this._sceneLoadingStates.get(sceneName);
if (!sceneState) {
logger.warn(
'Can\'t load resource for unknown scene: "' + sceneName + '".'
);
return;
}
let parsedCount = 0;
for (const resourceName of sceneState.resourceNames) {
const resource = this._resources.get(resourceName);
if (!resource) {
logger.warn('Unable to find resource "' + resourceName + '".');
continue;
}
await this._processResource(resource); | @@ -28,10 +28,6 @@ namespace gdjs {
);
};
- const maxForegroundConcurrency = 20;
- const maxBackgroundConcurrency = 5;
- const maxAttempt = 3;
-
/**
* A task of pre-loading resources used by a scene.
*
@@ -104,10 +100,21 @@ namespace gdjs {
}
}
+ type PromiseError<T> = { item: T; error: Error };
+
+ type PromisePoolOutput<T, U> = {
+ results: Array<U>;
+ errors: Array<PromiseError<T>>;
+ };
+
/**
* Pre-load resources of any kind needed for a game or a scene.
*/
export class ResourceLoader {
+ static maxForegroundConcurrency = 20;
+ static maxBackgroundConcurrency = 5;
+ static maxAttempt = 3;
+
_runtimeGame: RuntimeGame;
/**
* All the resource of a game by resource name.
@@ -290,10 +297,10 @@ namespace gdjs {
onProgress: (loadingCount: integer, totalCount: integer) => void
): Promise<void> {
let loadedCount = 0;
- await processAndRetryIfNeededWithPromisePool(
+ await ResourceLoader.processAndRetryIfNeededWithPromisePool(
[...this._resources.values()],
- maxForegroundConcurrency,
- maxAttempt,
+ ResourceLoader.maxForegroundConcurrency,
+ ResourceLoader.maxAttempt,
async (resource) => {
await this._loadResource(resource);
await this._processResource(resource);
@@ -312,10 +319,10 @@ namespace gdjs {
onProgress: (loadingCount: integer, totalCount: integer) => void
): Promise<void> {
let loadedCount = 0;
- await processAndRetryIfNeededWithPromisePool(
+ await ResourceLoader.processAndRetryIfNeededWithPromisePool(
resourceNames,
- maxForegroundConcurrency,
- maxAttempt,
+ ResourceLoader.maxForegroundConcurrency,
+ ResourceLoader.maxAttempt,
async (resourceName) => {
const resource = this._resources.get(resourceName);
if (resource) {
@@ -348,10 +355,10 @@ namespace gdjs {
...this._globalResour | GDJS/Runtime/ResourceLoader.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | Fix throw error from load resource in managers for support retries logic | 8,060 | 4ian/GDevelop | 10,154 | JavaScript | ViktorVovk | |
return ensureIsArray({
data: response.data,
endpointName: '/subscription-plan-pricing-system of Usage API',
});
}
return ensureIsArray({
data: (await apiClient.get('/subscription-plan-pricing-system', {
params,
})).data,
endpointName: '/subscription-plan-pricing-system of Usage API',
});
};
export const getUserUsages = async (
getAuthorizationHeader: () => Promise<string>,
userId: string
): Promise<Usages> => {
const authorizationHeader = await getAuthorizationHeader();
const response = await apiClient.get('/usage', {
params: {
userId,
},
headers: {
Authorization: authorizationHeader,
},
});
return ensureIsArray({
data: response.data,
endpointName: '/usage of Usage API',
});
};
export const getUserEarningsBalance = async (
getAuthorizationHeader: () => Promise<string>,
userId: string
): Promise<UserEarningsBalance> => {
const authorizationHeader = await getAuthorizationHeader();
const response = await apiClient.get(`/user-earnings-balance`, {
params: {
userId,
},
headers: {
Authorization: authorizationHeader,
},
});
const userEarningsBalances = ensureIsArray({
data: response.data,
endpointName: '/user-earnings-balance of Usage API', | No issues found. | return ensureIsArray({
data: response.data,
endpointName: '/subscription-plan-pricing-system of Usage API',
});
}
return ensureIsArray({
data: (await apiClient.get('/subscription-plan-pricing-system', {
params,
})).data,
endpointName: '/subscription-plan-pricing-system of Usage API',
});
};
export const getUserUsages = async (
getAuthorizationHeader: () => Promise<string>,
userId: string
): Promise<Usages> => {
const authorizationHeader = await getAuthorizationHeader();
const response = await apiClient.get('/usage', {
params: {
userId,
},
headers: {
Authorization: authorizationHeader,
},
});
return ensureIsArray({
data: response.data,
endpointName: '/usage of Usage API',
});
};
export const getUserEarningsBalance = async (
getAuthorizationHeader: () => Promise<string>,
userId: string
): Promise<UserEarningsBalance> => {
const authorizationHeader = await getAuthorizationHeader();
const response = await apiClient.get(`/user-earnings-balance`, {
params: {
userId,
},
headers: {
Authorization: authorizationHeader,
},
});
const userEarningsBalances = ensureIsArray({
data: response.data,
endpointName: '/user-earnings-balance of Usage API', | @@ -514,17 +514,6 @@ export const changeUserSubscription = async (
});
};
-export const canSeamlesslyChangeSubscription = (
- subscription: Subscription,
- planId: string
-) => {
- // Bringing prices with different currencies prevents subscriptions to be changed seamlessly
- // on Stripe.
- // TODO: When the backend allows it, make it possible to seamlessly change subscription
- // if the currencies of the current and requested subscriptions match.
- return false;
-};
-
export const hasMobileAppStoreSubscriptionPlan = (
subscription: ?Subscription
): boolean => { | newIDE/app/src/Utils/GDevelopServices/Usage.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Make clearer warning when stopping subscription with a redemption code | 8,070 | 4ian/GDevelop | 10,154 | JavaScript | 4ian | |
(hasUnsavedChanges &&
currentCheckedOutVersionStatus.status === 'unsavedChanges')
) {
return currentCheckedOutVersionStatus;
}
return {
version: currentCheckedOutVersionStatus.version,
status: 'unsavedChanges',
};
});
},
[hasUnsavedChanges]
);
// This effect watches the isSavingProject flag to change the opened version status.
React.useEffect(
() => {
if (freezeWhileLoadingSpecificVersionRef.current) return;
setCheckedOutVersionStatus(currentCheckedOutVersionStatus => {
if (
!currentCheckedOutVersionStatus ||
(isSavingProject &&
currentCheckedOutVersionStatus.status === 'saving')
) {
return currentCheckedOutVersionStatus;
}
return isSavingProject
? {
version: currentCheckedOutVersionStatus.version,
status: 'saving',
}
: null;
});
},
[isSavingProject]
);
// This effect watches the project file metadata to reset the opened version
// if the project is closed.
React.useEffect(
() => {
if (!fileMetadata) {
setCheckedOutVersionStatus(null);
}
},
[fileMetadata]
);
const onLoadMoreVersions = React.useCallback( | No issues found. | (hasUnsavedChanges &&
currentCheckedOutVersionStatus.status === 'unsavedChanges')
) {
return currentCheckedOutVersionStatus;
}
return {
version: currentCheckedOutVersionStatus.version,
status: 'unsavedChanges',
};
});
},
[hasUnsavedChanges]
);
// This effect watches the isSavingProject flag to change the opened version status.
React.useEffect(
() => {
if (freezeWhileLoadingSpecificVersionRef.current) return;
setCheckedOutVersionStatus(currentCheckedOutVersionStatus => {
if (
!currentCheckedOutVersionStatus ||
(isSavingProject &&
currentCheckedOutVersionStatus.status === 'saving')
) {
return currentCheckedOutVersionStatus;
}
return isSavingProject
? {
version: currentCheckedOutVersionStatus.version,
status: 'saving',
}
: null;
});
},
[isSavingProject]
);
// This effect watches the project file metadata to reset the opened version
// if the project is closed.
React.useEffect(
() => {
if (!fileMetadata) {
setCheckedOutVersionStatus(null);
}
},
[fileMetadata]
);
const onLoadMoreVersions = React.useCallback( | @@ -13,7 +13,7 @@ import {
} from '../Utils/GDevelopServices/Project';
import type { FileMetadata, StorageProvider } from '../ProjectsStorage';
import AuthenticatedUserContext from '../Profile/AuthenticatedUserContext';
-import { canUseCloudProjectHistory } from '../Utils/GDevelopServices/Usage';
+import { getCloudProjectHistoryRetentionDays } from '../Utils/GDevelopServices/Usage';
import { Column, Line } from '../UI/Grid';
import VersionHistory, { type OpenedVersionStatus } from '.';
import UnsavedChangesContext from '../MainFrame/UnsavedChangesContext';
@@ -25,6 +25,7 @@ import PlaceholderError from '../UI/PlaceholderError';
import CloudStorageProvider from '../ProjectsStorage/CloudStorageProvider';
import GetSubscriptionCard from '../Profile/Subscription/GetSubscriptionCard';
import Text from '../UI/Text';
+import { extractGDevelopApiErrorStatusAndCode } from '../Utils/GDevelopServices/Errors';
const getCloudProjectFileMetadataIdentifier = (
storageProviderInternalName: string,
@@ -120,7 +121,7 @@ const useVersionHistory = ({
const storageProviderInternalName = storageProvider.internalName;
const isCloudProject =
storageProviderInternalName === CloudStorageProvider.internalName;
- const isUserAllowedToSeeVersionHistory = canUseCloudProjectHistory(limits);
+ const historyRetentionDays = getCloudProjectHistoryRetentionDays(limits);
const [cloudProjectId, setCloudProjectId] = React.useState<?string>(
getCloudProjectFileMetadataIdentifier(
storageProviderInternalName,
@@ -133,8 +134,7 @@ const useVersionHistory = ({
] = React.useState<?number>(
isCloudProject && fileMetadata ? fileMetadata.lastModifiedDate : null
);
- const shouldFetchVersions =
- isCloudProject && isUserAllowedToSeeVersionHistory;
+ const shouldFetchVersions = isCloudProject && historyRetentionDays !== 0;
const latestVersionId =
state.versions && state.versions[0] ? state.versions[0].id : null;
const authenticatedUserId = profile | newIDE/app/src/VersionHistory/UseVersionHistory.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | New limits for cloud projects history | 8,077 | 4ian/GDevelop | 10,154 | JavaScript | ClementPasteau | |
return property;
}
static extractBooleanProperty(
anything: any,
propertyName: string
): boolean | null {
const object = this.extractObject(anything);
if (!object) return null;
const property = anything[propertyName];
if (typeof property !== 'boolean') return null;
return property;
}
static extractObjectProperty(
anything: any,
propertyName: string
): Object | null {
const object = this.extractObject(anything);
if (!object) return null;
const property = anything[propertyName];
return this.extractObject(property);
}
static extractArrayProperty(
anything: any,
propertyName: string
): Array<any> | null {
const object = this.extractObject(anything);
if (!object) return null;
const property = anything[propertyName];
return this.extractArray(property);
}
static extractObject(anything: any): Object | null {
if (
anything === null ||
anything === undefined ||
typeof anything !== 'object' ||
Array.isArray(anything)
)
return null;
return anything; | No issues found. | return property;
}
static extractBooleanProperty(
anything: any,
propertyName: string
): boolean | null {
const object = this.extractObject(anything);
if (!object) return null;
const property = anything[propertyName];
if (typeof property !== 'boolean') return null;
return property;
}
static extractObjectProperty(
anything: any,
propertyName: string
): Object | null {
const object = this.extractObject(anything);
if (!object) return null;
const property = anything[propertyName];
return this.extractObject(property);
}
static extractArrayProperty(
anything: any,
propertyName: string
): Array<any> | null {
const object = this.extractObject(anything);
if (!object) return null;
const property = anything[propertyName];
return this.extractArray(property);
}
static extractObject(anything: any): Object | null {
if (
anything === null ||
anything === undefined ||
typeof anything !== 'object' ||
Array.isArray(anything)
)
return null;
return anything; | @@ -97,4 +97,24 @@ export class SafeExtractor {
return anything;
}
+
+ static extractNumberOrStringOrBooleanProperty(
+ anything: any,
+ propertyName: string
+ ): number | string | boolean | null {
+ const object = this.extractObject(anything);
+ if (!object) return null;
+
+ const property = anything[propertyName];
+
+ if (
+ typeof property === 'number' ||
+ typeof property === 'string' ||
+ typeof property === 'boolean'
+ ) {
+ return property;
+ }
+
+ return null;
+ }
} | newIDE/app/src/Utils/SafeExtractor.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | feat: Project-specific Editor Settings | 8,101 | 4ian/GDevelop | 10,154 | JavaScript | malec-palec | |
return badResource;
}
const Resource &ResourcesContainer::GetResourceAt(std::size_t index) const {
if (index < resources.size())
return *resources[index];
return badResource;
}
void ResourcesContainer::MoveResource(std::size_t oldIndex,
std::size_t newIndex) {
if (oldIndex >= resources.size() || newIndex >= resources.size())
return;
auto resource = resources[oldIndex];
resources.erase(resources.begin() + oldIndex);
resources.insert(resources.begin() + newIndex, resource);
}
std::shared_ptr<gd::Resource>
ResourcesContainer::GetResourceSPtr(const gd::String &name) {
for (std::size_t i = 0; i < resources.size(); ++i) {
if (resources[i]->GetName() == name)
return resources[i];
}
return std::shared_ptr<gd::Resource>();
}
void ResourcesContainer::RenameResource(const gd::String& oldName,
const gd::String& newName) {
for (std::size_t i = 0; i < resources.size(); ++i) {
if (resources[i]->GetName() == oldName) resources[i]->SetName(newName);
}
}
void ResourcesContainer::RemoveResource(const gd::String &name) {
for (std::size_t i = 0; i < resources.size();) {
if (resources[i] != std::shared_ptr<Resource>() &&
resources[i]->GetName() == name)
resources.erase(resources.begin() + i);
else
++i;
}
}
void ResourcesContainer::UnserializeFrom(const SerializerElement &element) {
resources.clear();
const SerializerElement &resourcesElement = | No issues found. |
return badResource;
}
const Resource &ResourcesContainer::GetResourceAt(std::size_t index) const {
if (index < resources.size())
return *resources[index];
return badResource;
}
void ResourcesContainer::MoveResource(std::size_t oldIndex,
std::size_t newIndex) {
if (oldIndex >= resources.size() || newIndex >= resources.size())
return;
auto resource = resources[oldIndex];
resources.erase(resources.begin() + oldIndex);
resources.insert(resources.begin() + newIndex, resource);
}
std::shared_ptr<gd::Resource>
ResourcesContainer::GetResourceSPtr(const gd::String &name) {
for (std::size_t i = 0; i < resources.size(); ++i) {
if (resources[i]->GetName() == name)
return resources[i];
}
return std::shared_ptr<gd::Resource>();
}
void ResourcesContainer::RenameResource(const gd::String& oldName,
const gd::String& newName) {
for (std::size_t i = 0; i < resources.size(); ++i) {
if (resources[i]->GetName() == oldName) resources[i]->SetName(newName);
}
}
void ResourcesContainer::RemoveResource(const gd::String &name) {
for (std::size_t i = 0; i < resources.size();) {
if (resources[i] != std::shared_ptr<Resource>() &&
resources[i]->GetName() == name)
resources.erase(resources.begin() + i);
else
++i;
}
}
void ResourcesContainer::UnserializeFrom(const SerializerElement &element) {
resources.clear();
const SerializerElement &resourcesElement = | @@ -311,6 +311,20 @@ ResourcesContainer::GetResourcePosition(const gd::String &name) const {
return gd::String::npos;
}
+Resource &ResourcesContainer::GetResourceAt(std::size_t index) {
+ if (index < resources.size())
+ return *resources[index];
+
+ return badResource;
+}
+
+const Resource &ResourcesContainer::GetResourceAt(std::size_t index) const {
+ if (index < resources.size())
+ return *resources[index];
+
+ return badResource;
+}
+
void ResourcesContainer::MoveResource(std::size_t oldIndex,
std::size_t newIndex) {
if (oldIndex >= resources.size() || newIndex >= resources.size()) | Core/GDCore/Project/ResourcesContainer.cpp | 0 | C++ | 1 | none | 16 | 51 | 51 | true | QoL Resource tab with shortcuts | 8,115 | 4ian/GDevelop | 10,154 | JavaScript | Bouh | |
},
};
this._isAnimationComplete = false;
this._rendererObject.state.addListener(onCompleteListener);
this._rendererObject.state.setAnimation(0, animation, loop);
this._rendererObject.update(0);
}
}
getAnimationDuration(sourceAnimationName: string) {
if (!isSpine(this._rendererObject)) {
return 0;
}
const animation =
this._rendererObject.spineData.findAnimation(sourceAnimationName);
return animation ? animation.duration : 0;
}
getAnimationElapsedTime(): number {
if (!isSpine(this._rendererObject)) {
return 0;
}
const tracks = this._rendererObject.state.tracks;
if (tracks.length === 0) {
return 0;
}
// This should be fine because only 1 track is used.
const track = tracks[0];
// @ts-ignore TrackEntry.getAnimationTime is not exposed.
return track.getAnimationTime();
}
setAnimationElapsedTime(time: number): void {
if (!isSpine(this._rendererObject)) {
return;
}
const tracks = this._rendererObject.state.tracks;
if (tracks.length === 0) {
return;
}
const track = tracks[0];
track.trackTime = time;
}
isAnimationComplete(): boolean {
if (!isSpine(this._rendererObject)) {
return true;
}
const track = this._rendererObject.state.tracks[0];
if (!track) { | No issues found. | },
};
this._isAnimationComplete = false;
this._rendererObject.state.addListener(onCompleteListener);
this._rendererObject.state.setAnimation(0, animation, loop);
this._rendererObject.update(0);
}
}
getAnimationDuration(sourceAnimationName: string) {
if (!isSpine(this._rendererObject)) {
return 0;
}
const animation =
this._rendererObject.spineData.findAnimation(sourceAnimationName);
return animation ? animation.duration : 0;
}
getAnimationElapsedTime(): number {
if (!isSpine(this._rendererObject)) {
return 0;
}
const tracks = this._rendererObject.state.tracks;
if (tracks.length === 0) {
return 0;
}
// This should be fine because only 1 track is used.
const track = tracks[0];
// @ts-ignore TrackEntry.getAnimationTime is not exposed.
return track.getAnimationTime();
}
setAnimationElapsedTime(time: number): void {
if (!isSpine(this._rendererObject)) {
return;
}
const tracks = this._rendererObject.state.tracks;
if (tracks.length === 0) {
return;
}
const track = tracks[0];
track.trackTime = time;
}
isAnimationComplete(): boolean {
if (!isSpine(this._rendererObject)) {
return true;
}
const track = this._rendererObject.state.tracks[0];
if (!track) { | @@ -12,6 +12,13 @@ namespace gdjs {
computeWorldRotation(bone: pixi_spine.IBone): number;
}
+ interface IExtendedBone extends pixi_spine.IBone {
+ scaleX: number;
+ scaleY: number;
+ rotation: number;
+ parent: IExtendedBone | null;
+ }
+
const isPointAttachment = (
attachment: pixi_spine.IAttachment
): attachment is IPointAttachment =>
@@ -219,21 +226,13 @@ namespace gdjs {
this._rendererObject.y
);
}
- const slot = this._rendererObject.skeleton.findSlot(slotName);
- if (!slot) {
- throw new Error(
- `Unable to find ${slotName} slot name for ${attachmentName} point attachment.`
- );
- }
- const attachment = this._rendererObject.skeleton.getAttachmentByName(
- slotName,
- attachmentName
- );
- if (!isPointAttachment(attachment)) {
- throw new Error(
- `Unable to find ${attachmentName} point attachment with ${slotName} slot name.`
+
+ const { slot, attachment } =
+ SpineRuntimeObjectPixiRenderer.getSlotAndAttachmentFromRenderObject(
+ attachmentName,
+ slotName,
+ this._rendererObject
);
- }
return new PIXI.Matrix()
.rotate(this._rendererObject.rotation)
@@ -244,6 +243,84 @@ namespace gdjs {
);
}
+ getPointAttachmentRotation(
+ attachmentName: string,
+ slotName?: string,
+ isWorld?: boolean
+ ): number {
+ if (!slotName) {
+ slotName = attachmentName;
+ }
+ if (!isSpine(this._rendererObject)) {
+ return this._object.angle;
+ }
+
+ const { slot, attachment } =
+ SpineRuntimeObjectPixiRenderer.getSlotAndAttachmentFromRenderObject(
+ attachmentName,
+ slotName,
+ this._rendererObject
+ );
+
+ const bone = slot.bone as IExtendedBone;
+
+ if (isWorld) {
+ return (
+ gdjs.toDegrees(this._rendererObject.rotation) +
+ | Extensions/Spine/spineruntimeobject-pixi-renderer.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | Add point attachment rotation and scale expression for spine | 8,125 | 4ian/GDevelop | 10,154 | JavaScript | ViktorVovk | |
}}
value={getFieldValue({ instances, field })}
floatingLabelText={getFieldLabel({ instances, field })}
floatingLabelFixed
helperMarkdownText={getFieldDescription(field)}
multiline
style={styles.field}
/>
);
} else {
const {
onEditButtonBuildMenuTemplate,
onEditButtonClick,
setValue,
} = field;
return (
<TextFieldWithButtonLayout
key={field.name}
renderTextField={() => (
<SemiControlledTextField
value={getFieldValue({
instances,
field,
mixedValueFallback: '(Multiple values)',
})}
id={field.name}
floatingLabelText={getFieldLabel({ instances, field })}
floatingLabelFixed
helperMarkdownText={getFieldDescription(field)}
onChange={newValue => {
instances.forEach(i => setValue(i, newValue || ''));
_onInstancesModified(instances);
}}
style={styles.field}
disabled={getDisabled({ instances, field })}
/>
)}
renderButton={style =>
onEditButtonClick && !onEditButtonBuildMenuTemplate ? (
<RaisedButton
style={style}
primary
disabled={instances.length !== 1}
icon={<Edit />}
label={<Trans>Edit</Trans>}
onClick={onEditButtonClick}
/>
) : onEditButtonBuildMenuTemplate ? (
<RaisedButtonWithSplitMenu
style={style}
primary | No issues found. | }}
value={getFieldValue({ instances, field })}
floatingLabelText={getFieldLabel({ instances, field })}
floatingLabelFixed
helperMarkdownText={getFieldDescription(field)}
multiline
style={styles.field}
/>
);
} else {
const {
onEditButtonBuildMenuTemplate,
onEditButtonClick,
setValue,
} = field;
return (
<TextFieldWithButtonLayout
key={field.name}
renderTextField={() => (
<SemiControlledTextField
value={getFieldValue({
instances,
field,
mixedValueFallback: '(Multiple values)',
})}
id={field.name}
floatingLabelText={getFieldLabel({ instances, field })}
floatingLabelFixed
helperMarkdownText={getFieldDescription(field)}
onChange={newValue => {
instances.forEach(i => setValue(i, newValue || ''));
_onInstancesModified(instances);
}}
style={styles.field}
disabled={getDisabled({ instances, field })}
/>
)}
renderButton={style =>
onEditButtonClick && !onEditButtonBuildMenuTemplate ? (
<RaisedButton
style={style}
primary
disabled={instances.length !== 1}
icon={<Edit />}
label={<Trans>Edit</Trans>}
onClick={onEditButtonClick}
/>
) : onEditButtonBuildMenuTemplate ? (
<RaisedButtonWithSplitMenu
style={style}
primary | @@ -33,6 +33,7 @@ import {
type ValueField,
type ActionButton,
type SectionTitle,
+ type Title,
type ResourceField,
type LeaderboardIdField,
type Instances,
@@ -92,39 +93,68 @@ const getDisabled = ({
: false;
};
+export const hasMixedValues = ({
+ instances,
+ field,
+}: {|
+ instances: Instances,
+ field: ValueField | Title | ActionButton,
+|}): boolean => {
+ if (!instances[0]) {
+ console.log(
+ 'hasMixedValues was called with an empty list of instances (or containing undefined). This is a bug that should be fixed'
+ );
+ return true;
+ }
+ const { getValue } = field;
+ if (!getValue) return false;
+
+ const value = getValue(instances[0]);
+ for (var i = 1; i < instances.length; ++i) {
+ if (value !== getValue(instances[i])) {
+ return true;
+ }
+ }
+ return false;
+};
+
/**
* Get the value for the given field across all instances.
* If one of the instances doesn't share the same value, returns the default value.
* If there is no instances, returns the default value.
* If the field does not have a `getValue` method, returns `null`.
*/
-const getFieldValue = ({
+export const getFieldValue = ({
instances,
field,
- defaultValue,
+ mixedValueFallback,
}: {|
instances: Instances,
- field: ValueField | ActionButton | SectionTitle,
- defaultValue?: any,
+ field: ValueField | Title,
+ mixedValueFallback?: any,
|}): any => {
if (!instances[0]) {
console.log(
'getFieldValue was called with an empty list of instances (or containing undefined). This is a bug that should be fixed'
);
- return defaultValue;
+ return mixedValueFallback;
}
-
- const { getValue } = field;
+ const { getValue, defaultValue } = field;
if (!getValue) return null;
+ if (
+ typeof mixedValueFallback !== 'undefined' &&
+ hasMixedValues({ instances, field })
+ ) {
+ return mixedValueFallback;
+ }
let value = getValue(instances[0]);
- for (var i = 1; i < instances | newIDE/app/src/PropertiesEditor/index.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Add a button to reset properties to their default values | 8,163 | 4ian/GDevelop | 10,154 | JavaScript | D8H | |
} else {
this._sendHotReloadLayers();
}
};
_onLayersVisibilityInEditorChanged = () => {
this._sendHotReloadLayers();
};
_onChooseLayer = (layerName: string) => {
this.setState({
chosenLayer: layerName,
});
const { previewDebuggerServer } = this.props;
if (previewDebuggerServer) {
previewDebuggerServer
.getExistingEmbeddedGameFrameDebuggerIds()
.forEach(debuggerId => {
previewDebuggerServer.sendMessage(debuggerId, {
command: 'setSelectedLayer',
payload: {
layerName,
},
});
});
}
};
_onSelectLayer = (layer: gdLayer | null) => {
this.setState({
selectedLayer: layer,
lastSelectionType: 'layer',
});
};
_onDeleteObjects = (
i18n: I18nType,
objectsWithContext: ObjectWithContext[],
done: boolean => void
) => {
const { project, layout, eventsBasedObject, onObjectsDeleted } = this.props;
objectsWithContext.forEach(objectWithContext => {
const { object, global } = objectWithContext;
// Unselect instances of the deleted object because these instances
// will be deleted by gd.WholeProjectRefactorer (and after that, they will
// be invalid references, as pointing to deleted objects).
this.instancesSelection.unselectInstancesOfObject(object.getName());
| No issues found. | } else {
this._sendHotReloadLayers();
}
};
_onLayersVisibilityInEditorChanged = () => {
this._sendHotReloadLayers();
};
_onChooseLayer = (layerName: string) => {
this.setState({
chosenLayer: layerName,
});
const { previewDebuggerServer } = this.props;
if (previewDebuggerServer) {
previewDebuggerServer
.getExistingEmbeddedGameFrameDebuggerIds()
.forEach(debuggerId => {
previewDebuggerServer.sendMessage(debuggerId, {
command: 'setSelectedLayer',
payload: {
layerName,
},
});
});
}
};
_onSelectLayer = (layer: gdLayer | null) => {
this.setState({
selectedLayer: layer,
lastSelectionType: 'layer',
});
};
_onDeleteObjects = (
i18n: I18nType,
objectsWithContext: ObjectWithContext[],
done: boolean => void
) => {
const { project, layout, eventsBasedObject, onObjectsDeleted } = this.props;
objectsWithContext.forEach(objectWithContext => {
const { object, global } = objectWithContext;
// Unselect instances of the deleted object because these instances
// will be deleted by gd.WholeProjectRefactorer (and after that, they will
// be invalid references, as pointing to deleted objects).
this.instancesSelection.unselectInstancesOfObject(object.getName());
| @@ -359,6 +359,16 @@ export default class SceneEditor extends React.Component<Props, State> {
}
componentDidMount() {
+ // Sync the saved gameEditorMode from instancesEditorSettings to MainFrame.
+ if (
+ this.props.isActive &&
+ this.state.instancesEditorSettings.gameEditorMode
+ ) {
+ this.props.setGameEditorMode(
+ this.state.instancesEditorSettings.gameEditorMode
+ );
+ }
+
this.resourceExternallyChangedCallbackId = registerOnResourceExternallyChangedCallback(
this.onResourceExternallyChanged.bind(this)
);
@@ -655,8 +665,8 @@ export default class SceneEditor extends React.Component<Props, State> {
if (editorDisplay.getName() === 'mosaic') {
this.props.setToolbar(
<MosaicEditorsDisplayToolbar
- gameEditorMode={this.props.gameEditorMode}
- setGameEditorMode={this.props.setGameEditorMode}
+ gameEditorMode={this.state.instancesEditorSettings.gameEditorMode}
+ setGameEditorMode={this.setGameEditorMode}
selectedInstancesCount={
this.instancesSelection.getSelectedInstances().length
}
@@ -735,6 +745,14 @@ export default class SceneEditor extends React.Component<Props, State> {
this.openSceneProperties(false);
}
if (!this.props.isActive && nextProps.isActive) {
+ // Sync the saved gameEditorMode from instancesEditorSettings to mainframe
+ // when the editor becomes active again
+ if (this.state.instancesEditorSettings.gameEditorMode) {
+ this.props.setGameEditorMode(
+ this.state.instancesEditorSettings.gameEditorMode
+ );
+ }
+
// When the scene is refocused, the selections are cleaned
// to avoid cases where we hold references to instances or objects
// deleted by something outside of the scene (for example,
@@ -792,6 +810,16 @@ export default class SceneEditor extends React.Component<Props, State> {
});
};
+ setGameEditorMod | newIDE/app/src/SceneEditor/index.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Save Editor Mode (2D/3D) per scene instead of globally | 8,169 | 4ian/GDevelop | 10,154 | JavaScript | ClementPasteau | |
gd::WholeProjectRefactorer::RenameParameter(
project, projectScopedContainers, eventsFunction,
parametersObjectsContainer, "MyObject", "MyRenamedObject");
REQUIRE(instruction.GetParameter(0).GetPlainString() ==
"MyRenamedObject");
REQUIRE(instruction2.GetParameter(0).GetPlainString() ==
"MyRenamedObject.GetObjectStringWith1Param(0)");
REQUIRE(instruction3.GetParameter(0).GetPlainString() ==
"MyExtension::GetVariableAsNumber(MyVariable.MyChild[MyRenamedObject.GetObjectStringWith1Param(0)])");
}
SECTION("(Free function) object parameter not renamed (in variable parameter)") {
gd::Project project;
gd::Platform platform;
SetupProjectWithDummyPlatform(project, platform);
auto &eventsExtension = SetupProjectWithEventsFunctionExtension(project);
auto &eventsFunction =
eventsExtension.GetEventsFunctions().InsertNewEventsFunction(
"MyFreeEventsFunction", 0);
eventsFunction.GetParameters()
.AddNewParameter("MyObject")
.GetValueTypeMetadata()
.SetName("objectList")
.SetExtraInfo("MyExtension::Sprite");
// Parameters can't actually be used in "variable" parameters.
auto &instruction = CreateInstructionWithVariableParameter(
project, eventsFunction.GetEvents(), "MyObject");
auto &instruction2 = CreateInstructionWithNumberParameter(
project, eventsFunction.GetEvents(),
"MyExtension::GetVariableAsNumber(MyObject)");
gd::ObjectsContainer parametersObjectsContainer(
gd::ObjectsContainer::SourceType::Function);
gd::VariablesContainer parameterVariablesContainer(
gd::VariablesContainer::SourceType::Parameters);
gd::ResourcesContainer parameterResourcesContainer(
gd::ResourcesContainer::SourceType::Parameters);
auto projectScopedContainers = gd::ProjectScopedContainers::
MakeNewProjectScopedContainersForFreeEventsFunction(
project, eventsExtension, eventsFunction,
parametersObjectsContainer, parameterVariablesContainer,
parameterResourcesContainer);
gd::WholeProjectRefactorer::RenameParameter(
project, projectScopedContainers, eventsFunction,
parametersObjectsContainer, "MyObject", "MyRenamedObject");
// "variable" parameters are left untouched.
REQUIRE(instruction.GetParameter(0).GetPlainString() ==
"MyObject"); | No issues found. | gd::WholeProjectRefactorer::RenameParameter(
project, projectScopedContainers, eventsFunction,
parametersObjectsContainer, "MyObject", "MyRenamedObject");
REQUIRE(instruction.GetParameter(0).GetPlainString() ==
"MyRenamedObject");
REQUIRE(instruction2.GetParameter(0).GetPlainString() ==
"MyRenamedObject.GetObjectStringWith1Param(0)");
REQUIRE(instruction3.GetParameter(0).GetPlainString() ==
"MyExtension::GetVariableAsNumber(MyVariable.MyChild[MyRenamedObject.GetObjectStringWith1Param(0)])");
}
SECTION("(Free function) object parameter not renamed (in variable parameter)") {
gd::Project project;
gd::Platform platform;
SetupProjectWithDummyPlatform(project, platform);
auto &eventsExtension = SetupProjectWithEventsFunctionExtension(project);
auto &eventsFunction =
eventsExtension.GetEventsFunctions().InsertNewEventsFunction(
"MyFreeEventsFunction", 0);
eventsFunction.GetParameters()
.AddNewParameter("MyObject")
.GetValueTypeMetadata()
.SetName("objectList")
.SetExtraInfo("MyExtension::Sprite");
// Parameters can't actually be used in "variable" parameters.
auto &instruction = CreateInstructionWithVariableParameter(
project, eventsFunction.GetEvents(), "MyObject");
auto &instruction2 = CreateInstructionWithNumberParameter(
project, eventsFunction.GetEvents(),
"MyExtension::GetVariableAsNumber(MyObject)");
gd::ObjectsContainer parametersObjectsContainer(
gd::ObjectsContainer::SourceType::Function);
gd::VariablesContainer parameterVariablesContainer(
gd::VariablesContainer::SourceType::Parameters);
gd::ResourcesContainer parameterResourcesContainer(
gd::ResourcesContainer::SourceType::Parameters);
auto projectScopedContainers = gd::ProjectScopedContainers::
MakeNewProjectScopedContainersForFreeEventsFunction(
project, eventsExtension, eventsFunction,
parametersObjectsContainer, parameterVariablesContainer,
parameterResourcesContainer);
gd::WholeProjectRefactorer::RenameParameter(
project, projectScopedContainers, eventsFunction,
parametersObjectsContainer, "MyObject", "MyRenamedObject");
// "variable" parameters are left untouched.
REQUIRE(instruction.GetParameter(0).GetPlainString() ==
"MyObject"); | @@ -1053,16 +1053,19 @@ SetupProjectWithEventsFunctionExtension(gd::Project &project) {
// Add a property:
eventsBasedBehavior.GetPropertyDescriptors()
.InsertNew("MyProperty", 0)
- .SetType("Number");
+ .SetType("Number")
+ .SetValue("0");
// Add a shared property:
eventsBasedBehavior.GetSharedPropertyDescriptors()
.InsertNew("MySharedProperty", 0)
- .SetType("Number");
+ .SetType("Number")
+ .SetValue("0");
// The same name is used for another shared property to ensure there is no name
// collision.
eventsBasedBehavior.GetSharedPropertyDescriptors()
.InsertNew("MyProperty", 0)
- .SetType("Number");
+ .SetType("Number")
+ .SetValue("0");
}
// Add a events based object
@@ -3660,6 +3663,37 @@ TEST_CASE("WholeProjectRefactorer", "[common]") {
"MyExtension::GetVariableAsNumber(MyVariable.MyChild[MyRenamedProperty])");
}
+ SECTION("(Events based behavior) property renamed (in objects)") {
+ gd::Project project;
+ gd::Platform platform;
+ SetupProjectWithDummyPlatform(project, platform);
+ auto &eventsExtension = SetupProjectWithEventsFunctionExtension(project);
+ auto &eventsBasedBehavior =
+ eventsExtension.GetEventsBasedBehaviors().Get("MyEventsBasedBehavior");
+ REQUIRE(eventsBasedBehavior.GetPropertyDescriptors().Has("MyProperty"));
+ auto &property =
+ eventsBasedBehavior.GetPropertyDescriptors().Get("MyProperty");
+
+ auto &layout = project.GetLayout("Scene");
+ auto &object = layout.GetObjects().GetObject("ObjectWithMyBehavior");
+ auto &behavior = object.GetBehavior("MyBehavior");
+ behavior.UpdateProperty("MyProperty", "123");
+ {
+ auto properties = behavior.GetProperties();
+ REQUIRE(properties.find("MyProperty") != properties.end());
+ REQUIRE(properties.at("MyProperty").GetValue() == "123");
+ }
+
+ gd::WholeProjectRefactorer::RenameEvent | Core/tests/WholeProjectRefactorer.cpp | 0 | C++ | 1 | none | 16 | 51 | 51 | true | Fix property value loss when renaming a property in the extension editor | 8,211 | 4ian/GDevelop | 10,154 | JavaScript | D8H | |
setIsPlaying(false);
}, []);
const onError = React.useCallback(
() => {
if (onSoundError) onSoundError();
},
[onSoundError]
);
React.useEffect(
() => {
if (!waveSurferRef.current && !mobileAudioRef.current) return;
if (isPlaying) {
if (waveSurferRef.current) waveSurferRef.current.play();
else if (mobileAudioRef.current) mobileAudioRef.current.play();
} else {
if (waveSurferRef.current) waveSurferRef.current.pause();
else if (mobileAudioRef.current) mobileAudioRef.current.pause();
}
},
[isPlaying]
);
const onPlayPause = React.useCallback(
(forcePlay?: boolean) => {
if (!soundSrc) return;
setIsPlaying(_isPlaying => forcePlay || !_isPlaying);
},
[soundSrc]
);
const onFinishPlaying = React.useCallback(() => {
setIsPlaying(false);
}, []);
React.useImperativeHandle(ref, () => ({
playPause: onPlayPause,
}));
const onTimeupdate = React.useCallback(() => {
setTime(_time => {
const playerCurrentTime = mobileAudioRef.current
? mobileAudioRef.current.currentTime
: waveSurferRef.current
? waveSurferRef.current.getCurrentTime()
: null;
if (playerCurrentTime === null || _time === playerCurrentTime) {
return _time;
}
return playerCurrentTime; | No issues found. | setIsPlaying(false);
}, []);
const onError = React.useCallback(
() => {
if (onSoundError) onSoundError();
},
[onSoundError]
);
React.useEffect(
() => {
if (!waveSurferRef.current && !mobileAudioRef.current) return;
if (isPlaying) {
if (waveSurferRef.current) waveSurferRef.current.play();
else if (mobileAudioRef.current) mobileAudioRef.current.play();
} else {
if (waveSurferRef.current) waveSurferRef.current.pause();
else if (mobileAudioRef.current) mobileAudioRef.current.pause();
}
},
[isPlaying]
);
const onPlayPause = React.useCallback(
(forcePlay?: boolean) => {
if (!soundSrc) return;
setIsPlaying(_isPlaying => forcePlay || !_isPlaying);
},
[soundSrc]
);
const onFinishPlaying = React.useCallback(() => {
setIsPlaying(false);
}, []);
React.useImperativeHandle(ref, () => ({
playPause: onPlayPause,
}));
const onTimeupdate = React.useCallback(() => {
setTime(_time => {
const playerCurrentTime = mobileAudioRef.current
? mobileAudioRef.current.currentTime
: waveSurferRef.current
? waveSurferRef.current.getCurrentTime()
: null;
if (playerCurrentTime === null || _time === playerCurrentTime) {
return _time;
}
return playerCurrentTime; | @@ -52,6 +52,7 @@ type Props = {|
title: string | null,
subtitle: React.Node,
onSoundLoaded: () => void,
+ onSoundError?: () => void,
onSkipForward?: () => void,
onSkipBack?: () => void,
|};
@@ -62,7 +63,15 @@ export type SoundPlayerInterface = {|
const SoundPlayer = React.forwardRef<Props, SoundPlayerInterface>(
(
- { soundSrc, onSoundLoaded, onSkipBack, onSkipForward, title, subtitle },
+ {
+ soundSrc,
+ onSoundLoaded,
+ onSoundError,
+ onSkipBack,
+ onSkipForward,
+ title,
+ subtitle,
+ },
ref
) => {
const gdevelopTheme = React.useContext(GDevelopThemeContext);
@@ -119,6 +128,13 @@ const SoundPlayer = React.forwardRef<Props, SoundPlayerInterface>(
setIsPlaying(false);
}, []);
+ const onError = React.useCallback(
+ () => {
+ if (onSoundError) onSoundError();
+ },
+ [onSoundError]
+ );
+
React.useEffect(
() => {
if (!waveSurferRef.current && !mobileAudioRef.current) return;
@@ -175,6 +191,7 @@ const SoundPlayer = React.forwardRef<Props, SoundPlayerInterface>(
audio.addEventListener('ended', onFinishPlaying);
audio.addEventListener('loadstart', onLoad);
audio.addEventListener('loadedmetadata', onAudioReady);
+ audio.addEventListener('error', onError);
mobileAudioRef.current = audio;
}
waveSurferRef.current = null;
@@ -183,7 +200,15 @@ const SoundPlayer = React.forwardRef<Props, SoundPlayerInterface>(
}
onLoad();
},
- [isMobile, soundSrc, onTimeupdate, onFinishPlaying, onLoad, onAudioReady]
+ [
+ isMobile,
+ soundSrc,
+ onTimeupdate,
+ onFinishPlaying,
+ onLoad,
+ onAudioReady,
+ onError,
+ ]
);
return (
@@ -250,6 +275,7 @@ const SoundPlayer = React.forwardRef<Props, SoundPlayerInterface>(
onTimeupdate={onTimeupdate}
| newIDE/app/src/UI/SoundPlayer/index.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Add audio preview in resources | 8,219 | 4ian/GDevelop | 10,154 | JavaScript | Bouh | |
}
edit(): void {
this.props.onEditLayer(this.layer);
this.props.onSelectLayer(null);
}
_isVisible(): boolean {
return this.layer.getVisibility();
}
_isLocked(): boolean {
return this.layer.isLocked();
}
_setVisibility(visible: boolean): void {
this.layer.setVisibility(visible);
this.props.triggerOnLayersModified();
}
_setLocked(isLocked: boolean): void {
this.layer.setLocked(isLocked);
this.props.triggerOnLayersModified();
}
getRightButton(i18n: I18nType) {
return [
{
icon: this._isVisible() ? <VisibilityIcon /> : <VisibilityOffIcon />,
label: i18n._(t`Visible`),
click: () => this._setVisibility(!this._isVisible()),
id: 'layer-visibility',
},
{
icon:
this._isLocked() || !this._isVisible() ? (
<LockIcon />
) : (
<LockOpenIcon />
),
label: i18n._(t`Locked`),
enabled: this._isVisible(),
click: () => this._setLocked(!this._isLocked()),
id: 'layer-lock',
},
];
}
buildMenuTemplate(i18n: I18nType, index: number) {
return [
{ | No issues found. | }
edit(): void {
this.props.onEditLayer(this.layer);
this.props.onSelectLayer(null);
}
_isVisible(): boolean {
return this.layer.getVisibility();
}
_isLocked(): boolean {
return this.layer.isLocked();
}
_setVisibility(visible: boolean): void {
this.layer.setVisibility(visible);
this.props.triggerOnLayersModified();
}
_setLocked(isLocked: boolean): void {
this.layer.setLocked(isLocked);
this.props.triggerOnLayersModified();
}
getRightButton(i18n: I18nType) {
return [
{
icon: this._isVisible() ? <VisibilityIcon /> : <VisibilityOffIcon />,
label: i18n._(t`Visible`),
click: () => this._setVisibility(!this._isVisible()),
id: 'layer-visibility',
},
{
icon:
this._isLocked() || !this._isVisible() ? (
<LockIcon />
) : (
<LockOpenIcon />
),
label: i18n._(t`Locked`),
enabled: this._isVisible(),
click: () => this._setLocked(!this._isLocked()),
id: 'layer-lock',
},
];
}
buildMenuTemplate(i18n: I18nType, index: number) {
return [
{ | @@ -148,7 +148,7 @@ export class LayerTreeViewItemContent implements TreeViewItemContent {
return [
{
label: i18n._(t`Rename`),
- click: () => this.props.editName(this.getId()),
+ click: () => this.props.editName(this.layer.getName()),
accelerator: 'F2',
enabled: !this._isBaseLayer(),
}, | newIDE/app/src/LayersList/LayerTreeViewItemContent.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Avoid crash when renaming with F2 to edit "Base layer" | 8,222 | 4ian/GDevelop | 10,154 | JavaScript | Bouh | |
/**
* You can optionally add sanity tests that will check the basic working
* of your extension behaviors/objects by instantiating behaviors/objects
* and setting the property to a given value.
*
* If you don't have any tests, you can simply return an empty array.
*
* But it is recommended to create tests for the behaviors/objects properties you created
* to avoid mistakes.
*/
runExtensionSanityTests: function (gd, extension) {
return [];
},
/**
* Register editors for objects.
*
* ℹ️ Run `node import-GDJS-Runtime.js` (in newIDE/app/scripts) if you make any change.
*/
registerEditorConfigurations: function (objectsEditorService) {},
/**
* Register renderers for instance of objects on the scene editor.
*
* ℹ️ Run `node import-GDJS-Runtime.js` (in newIDE/app/scripts) if you make any change.
*/
registerInstanceRenderers: function (objectsRenderingService) {
const { PIXI, RenderedInstance, gd } = objectsRenderingService;
class RenderedSpineInstance extends RenderedInstance {
/** @type {pixi_spine.Spine | null} */
_spine = null;
/** @type {PIXI.Sprite} */
_placeholder;
_initialWidth = 256;
_initialHeight = 256;
_animationIndex = -1;
_spineOriginOffsetX = 0;
_spineOriginOffsetY = 0;
/** @type {string} */
_skinName = RenderedSpineInstance.getDefaultSkinName();
constructor(
project,
instance,
associatedObjectConfiguration,
pixiContainer,
pixiResourcesLoader
) {
super(
project,
instance, | No issues found. |
/**
* You can optionally add sanity tests that will check the basic working
* of your extension behaviors/objects by instantiating behaviors/objects
* and setting the property to a given value.
*
* If you don't have any tests, you can simply return an empty array.
*
* But it is recommended to create tests for the behaviors/objects properties you created
* to avoid mistakes.
*/
runExtensionSanityTests: function (gd, extension) {
return [];
},
/**
* Register editors for objects.
*
* ℹ️ Run `node import-GDJS-Runtime.js` (in newIDE/app/scripts) if you make any change.
*/
registerEditorConfigurations: function (objectsEditorService) {},
/**
* Register renderers for instance of objects on the scene editor.
*
* ℹ️ Run `node import-GDJS-Runtime.js` (in newIDE/app/scripts) if you make any change.
*/
registerInstanceRenderers: function (objectsRenderingService) {
const { PIXI, RenderedInstance, gd } = objectsRenderingService;
class RenderedSpineInstance extends RenderedInstance {
/** @type {pixi_spine.Spine | null} */
_spine = null;
/** @type {PIXI.Sprite} */
_placeholder;
_initialWidth = 256;
_initialHeight = 256;
_animationIndex = -1;
_spineOriginOffsetX = 0;
_spineOriginOffsetY = 0;
/** @type {string} */
_skinName = RenderedSpineInstance.getDefaultSkinName();
constructor(
project,
instance,
associatedObjectConfiguration,
pixiContainer,
pixiResourcesLoader
) {
super(
project,
instance, | @@ -214,6 +214,37 @@ module.exports = {
.useStandardParameters('number', gd.ParameterOptions.makeNewOptions())
.setFunctionName('getPointAttachmentRotationLocal');
+ object
+ .addExpressionAndCondition(
+ 'string',
+ 'getSkin',
+ _('Get skin name'),
+ _('the skin of the object'),
+ _('the skin'),
+ _('Animations and images'),
+ 'JsPlatform/Extensions/spine.svg'
+ )
+ .addParameter('object', _('Spine'), 'SpineObject')
+ .useStandardParameters(
+ 'string',
+ gd.ParameterOptions.makeNewOptions().setDescription(_('Skin name'))
+ )
+ .setFunctionName('getSkin');
+
+ object
+ .addAction(
+ 'SetSkin',
+ _('Set skin'),
+ _('Set the skin of a Spine object.'),
+ _('Set the skin of _PARAM0_ to _PARAM1_'),
+ _('Animations and images'),
+ 'JsPlatform/Extensions/spine.svg',
+ 'JsPlatform/Extensions/spine.svg'
+ )
+ .addParameter('object', _('Spine'), 'SpineObject')
+ .addParameter('objectSkinName', _('Skin name'))
+ .setFunctionName('setSkin');
+
return extension;
},
@@ -254,6 +285,8 @@ module.exports = {
_animationIndex = -1;
_spineOriginOffsetX = 0;
_spineOriginOffsetY = 0;
+ /** @type {string} */
+ _skinName = RenderedSpineInstance.getDefaultSkinName();
constructor(
project,
@@ -283,6 +316,10 @@ module.exports = {
this._loadSpine();
}
+ static getDefaultSkinName() {
+ return 'default';
+ }
+
static getThumbnail(project, resourcesLoader, objectConfiguration) {
return 'JsPlatform/Extensions/spine.svg';
}
@@ -299,6 +336,21 @@ module.exports = {
this._loadSpine();
}
+ // Apply skin if it changed.
+ const skinName = object.getSkinName();
+ if (this._skinName !== skinName && this._spine) {
+ this._skinName = skinName;
+ tr | Extensions/Spine/JsExtension.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | feat: Add support for skin management in Spine objects | 8,229 | 4ian/GDevelop | 10,154 | JavaScript | ViktorVovk | |
this.props.onRenameLayer(oldName, newName);
}
edit(): void {
this.props.onEditLayer(this.layer);
this.props.onSelectLayer(null);
}
_isVisible(): boolean {
return this.layer.getVisibility();
}
_isLocked(): boolean {
return this.layer.isLocked();
}
_setVisibility(visible: boolean): void {
this.layer.setVisibility(visible);
this.props.triggerOnLayersModified();
}
_setLocked(isLocked: boolean): void {
this.layer.setLocked(isLocked);
this.props.triggerOnLayersModified();
}
getRightButton(i18n: I18nType): any {
return [
{
icon: this._isVisible() ? <VisibilityIcon /> : <VisibilityOffIcon />,
label: i18n._(t`Visible`),
click: () => this._setVisibility(!this._isVisible()),
id: 'layer-visibility',
},
{
icon:
this._isLocked() || !this._isVisible() ? (
<LockIcon />
) : (
<LockOpenIcon />
),
label: i18n._(t`Locked`),
enabled: this._isVisible(),
click: () => this._setLocked(!this._isLocked()),
id: 'layer-lock',
},
];
}
buildMenuTemplate(i18n: I18nType, index: number): any {
return [ | No issues found. | this.props.onRenameLayer(oldName, newName);
}
edit(): void {
this.props.onEditLayer(this.layer);
this.props.onSelectLayer(null);
}
_isVisible(): boolean {
return this.layer.getVisibility();
}
_isLocked(): boolean {
return this.layer.isLocked();
}
_setVisibility(visible: boolean): void {
this.layer.setVisibility(visible);
this.props.triggerOnLayersModified();
}
_setLocked(isLocked: boolean): void {
this.layer.setLocked(isLocked);
this.props.triggerOnLayersModified();
}
getRightButton(i18n: I18nType): any {
return [
{
icon: this._isVisible() ? <VisibilityIcon /> : <VisibilityOffIcon />,
label: i18n._(t`Visible`),
click: () => this._setVisibility(!this._isVisible()),
id: 'layer-visibility',
},
{
icon:
this._isLocked() || !this._isVisible() ? (
<LockIcon />
) : (
<LockOpenIcon />
),
label: i18n._(t`Locked`),
enabled: this._isVisible(),
click: () => this._setLocked(!this._isLocked()),
id: 'layer-lock',
},
];
}
buildMenuTemplate(i18n: I18nType, index: number): any {
return [ | @@ -149,7 +149,7 @@ export class LayerTreeViewItemContent implements TreeViewItemContent {
return [
{
label: i18n._(t`Rename`),
- click: () => this.props.editName(this.layer.getName()),
+ click: () => this.props.editName(this.getId()),
accelerator: 'F2',
enabled: !this._isBaseLayer(),
}, | newIDE/app/src/LayersList/LayerTreeViewItemContent.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Fix being able to rename a layer with shortcut | 8,309 | 4ian/GDevelop | 10,154 | JavaScript | ClementPasteau | |
project,
'Sprite',
'MySpriteEmpty',
objects.getObjectsCount()
);
// No animations added — getAnimationsCount() === 0
expect(
getObjectSizeAndOriginInfo(object, project, fakeAssetShortHeader1)
).toBeNull();
});
});
describe('TiledSpriteObject::TiledSprite', () => {
it('returns origin 0;0, center at image center, and size from the configuration', () => {
const objects = project.getObjects();
const object = objects.insertNewObject(
project,
'TiledSpriteObject::TiledSprite',
'MyTiledSprite',
objects.getObjectsCount()
);
const config = gd.asTiledSpriteConfiguration(object.getConfiguration());
config.setWidth(200);
config.setHeight(150);
expect(getObjectSizeAndOriginInfo(object, project, null)).toEqual({
size: '200x150',
origin: '0;0',
center: '100;75',
});
});
});
describe('PanelSpriteObject::PanelSprite', () => {
it('returns origin 0;0, center at image center, and size from the configuration', () => {
const objects = project.getObjects();
const object = objects.insertNewObject(
project,
'PanelSpriteObject::PanelSprite',
'MyPanelSprite',
objects.getObjectsCount()
);
const config = gd.asPanelSpriteConfiguration(object.getConfiguration());
config.setWidth(120);
config.setHeight(390);
expect(getObjectSizeAndOriginInfo(object, project, null)).toEqual({
size: '120x390',
origin: '0;0',
center: '60;195', | No issues found. | project,
'Sprite',
'MySpriteEmpty',
objects.getObjectsCount()
);
// No animations added — getAnimationsCount() === 0
expect(
getObjectSizeAndOriginInfo(object, project, fakeAssetShortHeader1)
).toBeNull();
});
});
describe('TiledSpriteObject::TiledSprite', () => {
it('returns origin 0;0, center at image center, and size from the configuration', () => {
const objects = project.getObjects();
const object = objects.insertNewObject(
project,
'TiledSpriteObject::TiledSprite',
'MyTiledSprite',
objects.getObjectsCount()
);
const config = gd.asTiledSpriteConfiguration(object.getConfiguration());
config.setWidth(200);
config.setHeight(150);
expect(getObjectSizeAndOriginInfo(object, project, null)).toEqual({
size: '200x150',
origin: '0;0',
center: '100;75',
});
});
});
describe('PanelSpriteObject::PanelSprite', () => {
it('returns origin 0;0, center at image center, and size from the configuration', () => {
const objects = project.getObjects();
const object = objects.insertNewObject(
project,
'PanelSpriteObject::PanelSprite',
'MyPanelSprite',
objects.getObjectsCount()
);
const config = gd.asPanelSpriteConfiguration(object.getConfiguration());
config.setWidth(120);
config.setHeight(390);
expect(getObjectSizeAndOriginInfo(object, project, null)).toEqual({
size: '120x390',
origin: '0;0',
center: '60;195', | @@ -0,0 +1,250 @@
+// @flow
+import { fakeAssetShortHeader1 } from '../fixtures/GDevelopServicesTestData';
+import { getObjectSizeAndOriginInfo } from './Utils';
+
+const gd: libGDevelop = global.gd;
+
+describe('getObjectSizeAndOriginInfo', () => {
+ let project: gdProject;
+
+ beforeEach(() => {
+ // $FlowFixMe[invalid-constructor]
+ project = new gd.ProjectHelper.createNewGDJSProject();
+ });
+
+ afterEach(() => {
+ project.delete();
+ });
+
+ describe('Sprite', () => {
+ it('returns origin and center from first frame, and size from the asset short header', () => {
+ const objects = project.getObjects();
+ const object = objects.insertNewObject(
+ project,
+ 'Sprite',
+ 'MySprite',
+ objects.getObjectsCount()
+ );
+ const spriteConfig = gd.asSpriteConfiguration(object.getConfiguration());
+ const animation = new gd.Animation();
+ animation.setDirectionsCount(1);
+ const sprite = new gd.Sprite();
+ sprite.getOrigin().setX(10);
+ sprite.getOrigin().setY(20);
+ // Leave center as default (isDefaultCenterPoint = true)
+ animation.getDirection(0).addSprite(sprite);
+ spriteConfig.getAnimations().addAnimation(animation);
+
+ expect(
+ getObjectSizeAndOriginInfo(object, project, fakeAssetShortHeader1)
+ ).toEqual({
+ size: '36x36',
+ origin: '10;20',
+ center: '18;18', // fakeAssetShortHeader1 is 36x36, so center = 18;18
+ });
+ });
+
+ it('returns a custom center when the sprite has one set explicitly', () => {
+ const objects = project.getObjects();
+ const object = objects.insertNewObject(
+ project,
+ 'Sprite',
+ 'MySpriteCustomCenter',
+ objects.getObjectsCount()
+ );
+ const spriteConfig = gd.asSpriteConfiguration(object.getConfiguration());
+ const animation = new gd.Animation();
+ animation.setDirectionsCount(1);
+ const sprite = new gd.Sprite();
+ | newIDE/app/src/EditorFunctions/Utils.spec.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Improve details of center/origin when a common object is created by the AI | 8,322 | 4ian/GDevelop | 10,154 | JavaScript | ClementPasteau | |
// Alamofire.swift
//
// Copyright (c) 2014 Alamofire (http://alamofire.org)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public struct Alamofire {
// HTTP Method Definitions; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
public enum Method: String {
case OPTIONS = "OPTIONS"
case GET = "GET"
case HEAD = "HEAD"
case POST = "POST"
case PUT = "PUT"
case PATCH = "PATCH"
case DELETE = "DELETE"
case TRACE = "TRACE"
case CONNECT = "CONNECT"
}
public enum ParameterEncoding {
case URL
case JSON(options: NSJSONWritingOptions)
case PropertyList(format: NSPropertyListFormat, options: NSPropertyListWriteOptions)
func encode(request: NSURLRequest, parameters: [String: AnyObject]?) -> (NSURLRequest, NSError?) {
if parameters == nil {
return (request, nil)
}
var mutableRequest: NSMutableURLRequest! = request.mutableCopy() as NSMutableURLRequest
var error: NSError? = nil
switch self {
case .URL:
func query(parameters: [String: AnyObject]) -> String! {
func queryComponents(key: String, value: AnyObject) -> [(String, String)] {
func dictionaryQueryComponents(key: String, dictionary: [String: AnyObject]) -> [(String, String)] {
var components: [(String, String)] = []
for (nestedKey, value) in dictionary {
components += queryComponents("\(key)[\(nestedKey)]", value)
}
return components
}
func arrayQueryComponents(key: String, array: [AnyObject]) -> [(String, String)] {
var components: [(String, String)] = []
for value in array {
components += queryComponents("\(key)[]", value)
}
return components
}
var components: [(String, String)] = []
if let dictionary = value as? [String: AnyObject] {
components += dictionaryQueryComponents(key, dictionary)
} else if let array = value as? [AnyObject] {
components += arrayQueryComponents(key, array)
} else {
components.append(key, "\(value)")
}
return components
}
var components: [(String, String)] = []
for key in sorted(Array(parameters.keys), <) {
let value: AnyObject! = parameters[key]
components += queryComponents(key, value)
}
return join("&", components.map{"\($0)=\($1)"} as [String])
}
func encodesParametersInURL(method: Method) -> Bool {
switch method {
case .GET, .HEAD, .DELETE:
return true
default:
return false
}
}
if encodesParametersInURL(Method.fromRaw(request.HTTPMethod)!) {
let URLComponents = NSURLComponents(URL: mutableRequest.URL, resolvingAgainstBaseURL: false)
URLComponents.query = (URLComponents.query ? URLComponents.query + "&" : "") + query(parameters!)
mutableRequest.URL = URLComponents.URL
} else {
if !mutableRequest.valueForHTTPHeaderField("Content-Type") {
mutableRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
}
mutableRequest.HTTPBody = query(parameters!).dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
}
case .JSON(let options):
let data = NSJSONSerialization.dataWithJSONObject(parameters, options: options, error: &error)
if data {
let charset = CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding))
mutableRequest.setValue("application/json; charset=\(charset)", forHTTPHeaderField: "Content-Type")
mutableRequest.HTTPBody = data
}
case .PropertyList(let (format, options)):
let data = NSPropertyListSerialization.dataWithPropertyList(parameters, format: format, options: options, error: &error)
if data {
let charset = CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
mutableRequest.setValue("application/x-plist; charset=\(charset)", forHTTPHeaderField: "Content-Type")
mutableRequest.HTTPBody = data
}
}
return (mutableRequest, error)
}
}
// MARK: -
class Manager {
class var sharedInstance: Manager {
struct Singleton {
static let instance = Manager()
}
return Singleton.instance
}
let delegate: SessionDelegate
let session: NSURLSession!
let operationQueue: NSOperationQueue = NSOperationQueue()
var automaticallyStartsRequests: Bool = true
lazy var defaultHeaders: [String: String] = {
// Accept-Language HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3
let acceptEncoding: String = "gzip;q=1.0,compress;q=0.5"
// Accept-Language HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
let acceptLanguage: String = {
var components: [String] = []
for (index, languageCode) in enumerate(NSLocale.preferredLanguages() as [String]) {
let q = 1.0 - (Double(index) * 0.1)
components.append("\(languageCode);q=\(q)")
if q <= 0.5 {
break
}
}
return components.reduce("", {$0 == "" ? $1 : "\($0),\($1)"})
}()
// User-Agent Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43
let userAgent: String = {
if let info = NSBundle.mainBundle().infoDictionary {
let executable: AnyObject? = info[kCFBundleExecutableKey]
let bundle: AnyObject? = info[kCFBundleIdentifierKey]
let version: AnyObject? = info[kCFBundleVersionKey]
let os: AnyObject? = NSProcessInfo.processInfo()?.operatingSystemVersionString
var mutableUserAgent = NSMutableString(string: "\(executable!)/\(bundle!) (\(version!); OS \(os!))") as CFMutableString
let transform = NSString(string: "Any-Latin; Latin-ASCII; [:^ASCII:] Remove") as CFString
if CFStringTransform(mutableUserAgent, nil, transform, 0) == 1 {
return mutableUserAgent as NSString
}
}
return "Alamofire"
}()
return ["Accept-Encoding": acceptEncoding,
"Accept-Language": acceptLanguage,
"User-Agent": userAgent]
}()
required init(configuration: NSURLSessionConfiguration! = nil) {
self.delegate = SessionDelegate()
self.session = NSURLSession(configuration: configuration, delegate: self.delegate, delegateQueue: self.operationQueue)
}
deinit {
self.session.invalidateAndCancel()
}
// MARK: -
func request(request: NSURLRequest) -> Request {
var mutableRequest: NSMutableURLRequest! = request.mutableCopy() as NSMutableURLRequest
for (field, value) in self.defaultHeaders {
if !mutableRequest.valueForHTTPHeaderField(field){
mutableRequest.setValue(value, forHTTPHeaderField: field)
}
}
var dataTask: NSURLSessionDataTask?
dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
dataTask = self.session.dataTaskWithRequest(mutableRequest)
}
let request = Request(session: self.session, task: dataTask!)
self.delegate[request.delegate.task] = request.delegate
request.resume()
return request
}
class SessionDelegate: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate {
private var subdelegates: [Int: Request.TaskDelegate]
private subscript(task: NSURLSessionTask) -> Request.TaskDelegate? {
get {
return self.subdelegates[task.taskIdentifier]
}
set(newValue) {
self.subdelegates[task.taskIdentifier] = newValue
}
}
var sessionDidBecomeInvalidWithError: ((NSURLSession!, NSError!) -> Void)?
var sessionDidFinishEventsForBackgroundURLSession: ((NSURLSession!) -> Void)?
var sessionDidReceiveChallenge: ((NSURLSession!, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential!))?
var taskWillPerformHTTPRedirection: ((NSURLSession!, NSURLSessionTask!, NSHTTPURLResponse!, NSURLRequest!) -> (NSURLRequest!))?
var taskDidReceiveChallenge: ((NSURLSession!, NSURLSessionTask!, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
var taskDidSendBodyData: ((NSURLSession!, NSURLSessionTask!, Int64, Int64, Int64) -> Void)?
var taskNeedNewBodyStream: ((NSURLSession!, NSURLSessionTask!) -> (NSInputStream!))?
var dataTaskDidReceiveResponse: ((NSURLSession!, NSURLSessionDataTask!, NSURLResponse!) -> (NSURLSessionResponseDisposition))?
var dataTaskDidBecomeDownloadTask: ((NSURLSession!, NSURLSessionDataTask!) -> Void)?
var dataTaskDidReceiveData: ((NSURLSession!, NSURLSessionDataTask!, NSData!) -> Void)?
var dataTaskWillCacheResponse: ((NSURLSession!, NSURLSessionDataTask!, NSCachedURLResponse!) -> (NSCachedURLResponse))?
var downloadTaskDidFinishDownloadingToURL: ((NSURLSession!, NSURLSessionDownloadTask!, NSURL) -> (NSURL))?
var downloadTaskDidWriteData: ((NSURLSession!, NSURLSessionDownloadTask!, Int64, Int64, Int64) -> Void)?
var downloadTaskDidResumeAtOffset: ((NSURLSession!, NSURLSessionDownloadTask!, Int64, Int64) -> Void)?
required override init() {
self.subdelegates = Dictionary()
super.init()
}
// MARK: NSURLSessionDelegate
func URLSession(session: NSURLSession!, didBecomeInvalidWithError error: NSError!) {
self.sessionDidBecomeInvalidWithError?(session, error)
}
func URLSession(session: NSURLSession!, didReceiveChallenge challenge: NSURLAuthenticationChallenge!, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)!) {
if self.sessionDidReceiveChallenge != nil {
completionHandler(self.sessionDidReceiveChallenge!(session, challenge))
} else {
completionHandler(.PerformDefaultHandling, nil)
}
}
func URLSessionDidFinishEventsForBackgroundURLSession(session: NSURLSession!) {
self.sessionDidFinishEventsForBackgroundURLSession?(session)
}
// MARK: NSURLSessionTaskDelegate
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, willPerformHTTPRedirection response: NSHTTPURLResponse!, newRequest request: NSURLRequest!, completionHandler: ((NSURLRequest!) -> Void)!) {
var redirectRequest = request
if self.taskWillPerformHTTPRedirection != nil {
redirectRequest = self.taskWillPerformHTTPRedirection!(session, task, response, request)
}
completionHandler(redirectRequest)
}
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didReceiveChallenge challenge: NSURLAuthenticationChallenge!, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)!) {
if let delegate = self[task] {
delegate.URLSession(session, task: task, didReceiveChallenge: challenge, completionHandler: completionHandler)
} else {
self.URLSession(session, didReceiveChallenge: challenge, completionHandler: completionHandler)
}
}
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, needNewBodyStream completionHandler: ((NSInputStream!) -> Void)!) {
if let delegate = self[task] {
delegate.URLSession(session, task: task, needNewBodyStream: completionHandler)
}
}
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
if let delegate = self[task] as? Request.UploadTaskDelegate {
delegate.URLSession(session, task: task, didSendBodyData: bytesSent, totalBytesSent: totalBytesSent, totalBytesExpectedToSend: totalBytesExpectedToSend)
}
}
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didCompleteWithError error: NSError!) {
if let delegate = self[task] {
delegate.URLSession(session, task: task, didCompleteWithError: error)
}
}
// MARK: NSURLSessionDataDelegate
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didReceiveResponse response: NSURLResponse!, completionHandler: ((NSURLSessionResponseDisposition) -> Void)!) {
var disposition: NSURLSessionResponseDisposition = .Allow
if self.dataTaskDidReceiveResponse != nil {
disposition = self.dataTaskDidReceiveResponse!(session, dataTask, response)
}
completionHandler(disposition)
}
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask!) {
let downloadDelegate = Request.DownloadTaskDelegate(task: downloadTask)
self[downloadTask] = downloadDelegate
}
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didReceiveData data: NSData!) {
if let delegate = self[dataTask] as? Request.DataTaskDelegate {
delegate.URLSession(session, dataTask: dataTask, didReceiveData: data)
}
self.dataTaskDidReceiveData?(session, dataTask, data)
}
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, willCacheResponse proposedResponse: NSCachedURLResponse!, completionHandler: ((NSCachedURLResponse!) -> Void)!) {
var cachedResponse = proposedResponse
if self.dataTaskWillCacheResponse != nil {
cachedResponse = self.dataTaskWillCacheResponse!(session, dataTask, proposedResponse)
}
completionHandler(cachedResponse)
}
// MARK: NSURLSessionDownloadDelegate
func URLSession(session: NSURLSession!, downloadTask: NSURLSessionDownloadTask!, didFinishDownloadingToURL location: NSURL!) {
if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
delegate.URLSession(session, downloadTask: downloadTask, didFinishDownloadingToURL: location)
}
self.downloadTaskDidFinishDownloadingToURL?(session, downloadTask, location)
}
func URLSession(session: NSURLSession!, downloadTask: NSURLSessionDownloadTask!, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
delegate.URLSession(session, downloadTask: downloadTask, didWriteData: bytesWritten, totalBytesWritten: totalBytesWritten, totalBytesExpectedToWrite: totalBytesExpectedToWrite)
}
self.downloadTaskDidWriteData?(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
}
func URLSession(session: NSURLSession!, downloadTask: NSURLSessionDownloadTask!, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
delegate.URLSession(session, downloadTask: downloadTask, didResumeAtOffset: fileOffset, expectedTotalBytes: expectedTotalBytes)
}
self.downloadTaskDidResumeAtOffset?(session, downloadTask, fileOffset, expectedTotalBytes)
}
// MARK: NSObject
override func respondsToSelector(selector: Selector) -> Bool {
switch selector {
case "URLSession:didBecomeInvalidWithError:":
return (self.sessionDidBecomeInvalidWithError != nil)
case "URLSession:didReceiveChallenge:completionHandler:":
return (self.sessionDidReceiveChallenge != nil)
case "URLSessionDidFinishEventsForBackgroundURLSession:":
return (self.sessionDidFinishEventsForBackgroundURLSession != nil)
case "URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:":
return (self.taskWillPerformHTTPRedirection != nil)
case "URLSession:dataTask:didReceiveResponse:completionHandler:":
return (self.dataTaskDidReceiveResponse != nil)
case "URLSession:dataTask:willCacheResponse:completionHandler:":
return (self.dataTaskWillCacheResponse != nil)
default:
return self.dynamicType.instancesRespondToSelector(selector)
}
}
}
}
// MARK: -
class Request {
private let delegate: TaskDelegate
private var session: NSURLSession
private var task: NSURLSessionTask { return self.delegate.task }
var request: NSURLRequest! { return self.task.originalRequest }
var response: NSHTTPURLResponse! { return self.task.response as? NSHTTPURLResponse }
var progress: NSProgress? { return self.delegate.progress }
private init(session: NSURLSession, task: NSURLSessionTask) {
self.session = session
if task is NSURLSessionUploadTask {
self.delegate = UploadTaskDelegate(task: task)
} else if task is NSURLSessionDownloadTask {
self.delegate = DownloadTaskDelegate(task: task)
} else if task is NSURLSessionDataTask {
self.delegate = DataTaskDelegate(task: task)
} else {
self.delegate = TaskDelegate(task: task)
}
}
// MARK: Authentication
func authenticate(HTTPBasic user: String, password: String) -> Self {
let credential = NSURLCredential(user: user, password: password, persistence: .ForSession)
let protectionSpace = NSURLProtectionSpace(host: self.request.URL.host, port: 0, `protocol`: self.request.URL.scheme, realm: nil, authenticationMethod: NSURLAuthenticationMethodHTTPBasic)
return authenticate(usingCredential: credential, forProtectionSpace: protectionSpace)
}
func authenticate(usingCredential credential: NSURLCredential, forProtectionSpace protectionSpace: NSURLProtectionSpace) -> Self {
self.session.configuration.URLCredentialStorage.setCredential(credential, forProtectionSpace: protectionSpace)
return self
}
// MARK: Progress
func progress(closure: ((Int64, Int64, Int64) -> Void)? = nil) -> Self {
if let uploadDelegate = self.delegate as? UploadTaskDelegate {
uploadDelegate.uploadProgress = closure
} else if let downloadDelegate = self.delegate as? DownloadTaskDelegate {
downloadDelegate.downloadProgress = closure
}
return self
}
// MARK: Response
func response(completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
return response({ (request, response, data, error) in
return (data, error)
}, completionHandler: completionHandler)
}
func response(priority: Int = DISPATCH_QUEUE_PRIORITY_DEFAULT, queue: dispatch_queue_t? = nil, serializer: (NSURLRequest, NSHTTPURLResponse?, NSData?, NSError?) -> (AnyObject?, NSError?), completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
dispatch_async(self.delegate.queue, {
dispatch_async(dispatch_get_global_queue(priority, 0), {
let (responseObject: AnyObject?, error: NSError?) = serializer(self.request, self.response, self.delegate.data, self.delegate.error)
dispatch_async((queue != nil) ? queue : dispatch_get_main_queue(), {
completionHandler(self.request, self.response, responseObject, error)
})
})
})
return self
}
func suspend() {
self.task.suspend()
}
func resume() {
self.task.resume()
}
func cancel() {
if let downloadDelegate = self.delegate as? DownloadTaskDelegate {
downloadDelegate.downloadTask.cancelByProducingResumeData { (data) in
downloadDelegate.resumeData = data
}
} else {
self.task.cancel()
}
}
private class TaskDelegate: NSObject, NSURLSessionTaskDelegate {
let task: NSURLSessionTask
let queue: dispatch_queue_t?
let progress: NSProgress
var data: NSData! { return nil }
private(set) var error: NSError?
var taskWillPerformHTTPRedirection: ((NSURLSession!, NSURLSessionTask!, NSHTTPURLResponse!, NSURLRequest!) -> (NSURLRequest!))?
var taskDidReceiveChallenge: ((NSURLSession!, NSURLSessionTask!, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
var taskDidSendBodyData: ((NSURLSession!, NSURLSessionTask!, Int64, Int64, Int64) -> Void)?
var taskNeedNewBodyStream: ((NSURLSession!, NSURLSessionTask!) -> (NSInputStream!))?
init(task: NSURLSessionTask) {
self.task = task
self.progress = NSProgress(totalUnitCount: 0)
let label: String = "com.alamofire.task-\(task.taskIdentifier)"
let queue = dispatch_queue_create((label as NSString).UTF8String, DISPATCH_QUEUE_SERIAL)
dispatch_suspend(queue)
self.queue = queue
}
// MARK: NSURLSessionTaskDelegate
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, willPerformHTTPRedirection response: NSHTTPURLResponse!, newRequest request: NSURLRequest!, completionHandler: ((NSURLRequest!) -> Void)!) {
var redirectRequest = request
if self.taskWillPerformHTTPRedirection != nil {
redirectRequest = self.taskWillPerformHTTPRedirection!(session, task, response, request)
}
completionHandler(redirectRequest)
}
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didReceiveChallenge challenge: NSURLAuthenticationChallenge!, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)!) {
var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling
var credential: NSURLCredential?
if self.taskDidReceiveChallenge != nil {
(disposition, credential) = self.taskDidReceiveChallenge!(session, task, challenge)
} else {
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
// TODO: Incorporate Trust Evaluation & TLS Chain Validation
credential = NSURLCredential(forTrust: challenge.protectionSpace.serverTrust)
disposition = .UseCredential
}
}
completionHandler(disposition, credential)
}
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, needNewBodyStream completionHandler: ((NSInputStream!) -> Void)!) {
var bodyStream: NSInputStream?
if self.taskNeedNewBodyStream != nil {
bodyStream = self.taskNeedNewBodyStream!(session, task)
}
completionHandler(bodyStream)
}
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didCompleteWithError error: NSError!) {
dispatch_resume(self.queue)
}
}
private class DataTaskDelegate: TaskDelegate, NSURLSessionDataDelegate {
var dataTask: NSURLSessionDataTask! { return self.task as NSURLSessionDataTask }
private var mutableData: NSMutableData
override var data: NSData! {
return self.mutableData
}
var dataTaskDidReceiveResponse: ((NSURLSession!, NSURLSessionDataTask!, NSURLResponse!) -> (NSURLSessionResponseDisposition))?
var dataTaskDidBecomeDownloadTask: ((NSURLSession!, NSURLSessionDataTask!) -> Void)?
var dataTaskDidReceiveData: ((NSURLSession!, NSURLSessionDataTask!, NSData!) -> Void)?
var dataTaskWillCacheResponse: ((NSURLSession!, NSURLSessionDataTask!, NSCachedURLResponse!) -> (NSCachedURLResponse))?
override init(task: NSURLSessionTask) {
self.mutableData = NSMutableData()
super.init(task: task)
}
// MARK: NSURLSessionDataDelegate
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didReceiveResponse response: NSURLResponse!, completionHandler: ((NSURLSessionResponseDisposition) -> Void)!) {
var disposition: NSURLSessionResponseDisposition = .Allow
if self.dataTaskDidReceiveResponse != nil {
disposition = self.dataTaskDidReceiveResponse!(session, dataTask, response)
}
completionHandler(disposition)
}
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask!) {
self.dataTaskDidBecomeDownloadTask?(session, dataTask)
}
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didReceiveData data: NSData!) {
self.dataTaskDidReceiveData?(session, dataTask, data)
self.mutableData.appendData(data)
}
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, willCacheResponse proposedResponse: NSCachedURLResponse!, completionHandler: ((NSCachedURLResponse!) -> Void)!) {
var cachedResponse = proposedResponse
if self.dataTaskWillCacheResponse != nil {
cachedResponse = self.dataTaskWillCacheResponse!(session, dataTask, proposedResponse)
}
completionHandler(cachedResponse)
}
}
}
}
// MARK: - Upload
extension Alamofire.Manager {
private enum Uploadable {
case Data(NSURLRequest, NSData)
case File(NSURLRequest, NSURL)
case Stream(NSURLRequest, NSInputStream)
}
private func upload(uploadable: Uploadable) -> Alamofire.Request {
var uploadTask: NSURLSessionUploadTask!
var stream: NSInputStream?
switch uploadable {
case .Data(let request, let data):
uploadTask = self.session.uploadTaskWithRequest(request, fromData: data)
case .File(let request, let fileURL):
uploadTask = self.session.uploadTaskWithRequest(request, fromFile: fileURL)
case .Stream(let request, var stream):
uploadTask = self.session.uploadTaskWithStreamedRequest(request)
}
let request = Alamofire.Request(session: self.session, task: uploadTask)
if stream != nil {
request.delegate.taskNeedNewBodyStream = { _, _ in
return stream
}
}
self.delegate[request.delegate.task] = request.delegate
if self.automaticallyStartsRequests {
request.resume()
}
return request
}
// MARK: File
func upload(request: NSURLRequest, file: NSURL) -> Alamofire.Request {
return upload(.File(request, file))
}
// MARK: Data
func upload(request: NSURLRequest, data: NSData) -> Alamofire.Request {
return upload(.Data(request, data))
}
// MARK: Stream
func upload(request: NSURLRequest, stream: NSInputStream) -> Alamofire.Request {
return upload(.Stream(request, stream))
}
}
extension Alamofire.Request {
private class UploadTaskDelegate: DataTaskDelegate {
var uploadTask: NSURLSessionUploadTask! { return self.task as NSURLSessionUploadTask }
var uploadProgress: ((Int64, Int64, Int64) -> Void)!
// MARK: NSURLSessionTaskDelegate
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
if self.uploadProgress {
self.uploadProgress(bytesSent, totalBytesSent, totalBytesExpectedToSend)
}
self.progress.totalUnitCount = totalBytesExpectedToSend
self.progress.completedUnitCount = totalBytesSent
}
}
}
// MARK: - Download
extension Alamofire.Manager {
private enum Downloadable {
case Request(NSURLRequest)
case ResumeData(NSData)
}
private func download(downloadable: Downloadable, destination: (NSURL, NSHTTPURLResponse) -> (NSURL)) -> Alamofire.Request {
var downloadTask: NSURLSessionDownloadTask!
switch downloadable {
case .Request(let request):
downloadTask = self.session.downloadTaskWithRequest(request)
case .ResumeData(let resumeData):
downloadTask = self.session.downloadTaskWithResumeData(resumeData)
}
let request = Alamofire.Request(session: self.session, task: downloadTask)
if let downloadDelegate = request.delegate as? Alamofire.Request.DownloadTaskDelegate {
downloadDelegate.downloadTaskDidFinishDownloadingToURL = { (session, downloadTask, URL) in
return destination(URL, downloadTask.response as NSHTTPURLResponse)
}
}
self.delegate[request.delegate.task] = request.delegate
if self.automaticallyStartsRequests {
request.resume()
}
return request
}
// MARK: Request
func download(request: NSURLRequest, destination: (NSURL, NSHTTPURLResponse) -> (NSURL)) -> Alamofire.Request {
return download(.Request(request), destination: destination)
}
// MARK: Resume Data
func download(resumeData: NSData, destination: (NSURL, NSHTTPURLResponse) -> (NSURL)) -> Alamofire.Request {
return download(.ResumeData(resumeData), destination: destination)
}
}
extension Alamofire.Request {
class func suggestedDownloadDestination(directory: NSSearchPathDirectory = .DocumentDirectory, domain: NSSearchPathDomainMask = .UserDomainMask) -> (NSURL, NSHTTPURLResponse) -> (NSURL) {
return { (temporaryURL, response) -> (NSURL) in
if let directoryURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as? NSURL {
return directoryURL.URLByAppendingPathComponent(response.suggestedFilename)
}
return temporaryURL
}
}
private class DownloadTaskDelegate: TaskDelegate, NSURLSessionDownloadDelegate {
var downloadTask: NSURLSessionDownloadTask! { return self.task as NSURLSessionDownloadTask }
var downloadProgress: ((Int64, Int64, Int64) -> Void)?
var resumeData: NSData!
override var data: NSData! { return self.resumeData }
var downloadTaskDidFinishDownloadingToURL: ((NSURLSession!, NSURLSessionDownloadTask!, NSURL) -> (NSURL))?
var downloadTaskDidWriteData: ((NSURLSession!, NSURLSessionDownloadTask!, Int64, Int64, Int64) -> Void)?
var downloadTaskDidResumeAtOffset: ((NSURLSession!, NSURLSessionDownloadTask!, Int64, Int64) -> Void)?
// MARK: NSURLSessionDownloadDelegate
func URLSession(session: NSURLSession!, downloadTask: NSURLSessionDownloadTask!, didFinishDownloadingToURL location: NSURL!) {
if self.downloadTaskDidFinishDownloadingToURL != nil {
let destination = self.downloadTaskDidFinishDownloadingToURL!(session, downloadTask, location)
var fileManagerError: NSError?
NSFileManager.defaultManager().moveItemAtURL(location, toURL: destination, error: &fileManagerError)
// TODO: NSNotification on failure
}
}
func URLSession(session: NSURLSession!, downloadTask: NSURLSessionDownloadTask!, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
self.downloadTaskDidWriteData?(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
self.downloadProgress?(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
self.progress.totalUnitCount = totalBytesExpectedToWrite
self.progress.completedUnitCount = totalBytesWritten
}
func URLSession(session: NSURLSession!, downloadTask: NSURLSessionDownloadTask!, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
self.downloadTaskDidResumeAtOffset?(session, downloadTask, fileOffset, expectedTotalBytes)
self.progress.totalUnitCount = expectedTotalBytes
self.progress.completedUnitCount = fileOffset
}
}
}
// MARK: - Printable
extension Alamofire.Request: Printable {
var description: String {
var description = "\(self.request.HTTPMethod) \(self.request.URL)"
if self.response {
description += " (\(self.response?.statusCode))"
}
return description
}
}
extension Alamofire.Request: DebugPrintable {
func cURLRepresentation() -> String {
var components: [String] = ["$ curl -i"]
let URL = self.request.URL!
if self.request.HTTPMethod != "GET" {
components.append("-X \(self.request.HTTPMethod)")
}
if let credentialStorage = self.session.configuration.URLCredentialStorage {
let protectionSpace = NSURLProtectionSpace(host: URL.host, port: URL.port ? URL.port : 0, `protocol`: URL.scheme, realm: URL.host, authenticationMethod: NSURLAuthenticationMethodHTTPBasic)
if let credentials = credentialStorage.credentialsForProtectionSpace(protectionSpace)?.values.array {
if !credentials.isEmpty {
if let credential = credentials[0] as? NSURLCredential {
components.append("-u \(credential.user):\(credential.password)")
}
}
}
}
if let cookieStorage = self.session.configuration.HTTPCookieStorage {
if let cookies = cookieStorage.cookiesForURL(URL) as? [NSHTTPCookie] {
if !cookies.isEmpty {
let string = cookies.reduce(""){ $0 + "\($1.name)=\($1.value);" }
components.append("-b \"\(string.substringToIndex(string.endIndex.predecessor()))\"")
}
}
}
for (field, value) in self.request.allHTTPHeaderFields {
switch field {
case "Cookie":
continue
default:
components.append("-H \"\(field): \(value)\"")
}
}
if let HTTPBody = self.request.HTTPBody {
components.append("-d \"\(NSString(data: HTTPBody, encoding: NSUTF8StringEncoding))\"")
}
// TODO: -T arguments for files
components.append("\"\(URL.absoluteString)\"")
return join(" \\\n\t", components)
}
var debugDescription: String {
return self.cURLRepresentation()
}
}
// MARK: - Response Serializers
// MARK: String
extension Alamofire.Request {
class func stringResponseSerializer(encoding: NSStringEncoding = NSUTF8StringEncoding) -> (NSURLRequest, NSHTTPURLResponse?, NSData?, NSError?) -> (AnyObject?, NSError?) {
return { (_, _, data, error) in
let string = NSString(data: data, encoding: encoding)
return (string, error)
}
}
func responseString(completionHandler: (NSURLRequest, NSHTTPURLResponse?, String?, NSError?) -> Void) -> Self {
return responseString(completionHandler: completionHandler)
}
func responseString(encoding: NSStringEncoding = NSUTF8StringEncoding, completionHandler: (NSURLRequest, NSHTTPURLResponse?, String?, NSError?) -> Void) -> Self {
return response(serializer: Alamofire.Request.stringResponseSerializer(encoding: encoding), completionHandler: { request, response, string, error in
completionHandler(request, response, string as? String, error)
})
}
}
// MARK: JSON
extension Alamofire.Request {
class func JSONResponseSerializer(options: NSJSONReadingOptions = .AllowFragments) -> (NSURLRequest, NSHTTPURLResponse?, NSData?, NSError?) -> (AnyObject?, NSError?) {
return { (request, response, data, error) in
var serializationError: NSError?
let JSON: AnyObject! = NSJSONSerialization.JSONObjectWithData(data, options: options, error: &serializationError)
return (JSON, serializationError)
}
}
func responseJSON(completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
return responseJSON(completionHandler: completionHandler)
}
func responseJSON(options: NSJSONReadingOptions = .AllowFragments, completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
return response(serializer: Alamofire.Request.JSONResponseSerializer(options: options), completionHandler: { (request, response, JSON, error) in
completionHandler(request, response, JSON, error)
})
}
}
// MARK: Property List
extension Alamofire.Request {
class func propertyListResponseSerializer(options: NSPropertyListReadOptions = 0) -> (NSURLRequest, NSHTTPURLResponse?, NSData?, NSError?) -> (AnyObject?, NSError?) {
return { (request, response, data, error) in
var propertyListSerializationError: NSError?
let plist: AnyObject! = NSPropertyListSerialization.propertyListWithData(data, options: options, format: nil, error: &propertyListSerializationError)
return (plist, propertyListSerializationError)
}
}
func responsePropertyList(completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
return responsePropertyList(completionHandler: completionHandler)
}
func responsePropertyList(options: NSPropertyListReadOptions = 0, completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
return response(serializer: Alamofire.Request.propertyListResponseSerializer(options: options), completionHandler: { (request, response, plist, error) in
completionHandler(request, response, plist, error)
})
}
}
// MARK: - Convenience
extension Alamofire {
private static func URLRequest(method: Method, _ URL: String) -> NSURLRequest {
let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: URL))
mutableURLRequest.HTTPMethod = method.toRaw()
return mutableURLRequest
}
// MARK: Request
static func request(method: Method, _ URL: String, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL) -> Request {
return Manager.sharedInstance.request(encoding.encode(URLRequest(method, URL), parameters: parameters).0)
}
// MARK: Upload
static func upload(method: Method, _ URL: String, file: NSURL) -> Alamofire.Request {
return Manager.sharedInstance.upload(URLRequest(method, URL), file: file)
}
static func upload(method: Method, _ URL: String, data: NSData) -> Alamofire.Request {
return Manager.sharedInstance.upload(URLRequest(method, URL), data: data)
}
static func upload(method: Method, _ URL: String, stream: NSInputStream) -> Alamofire.Request {
return Manager.sharedInstance.upload(URLRequest(method, URL), stream: stream)
}
// MARK: Download
static func download(method: Method, _ URL: String, destination: (NSURL, NSHTTPURLResponse) -> (NSURL)) -> Alamofire.Request {
return Manager.sharedInstance.download(URLRequest(method, URL), destination: destination)
}
static func download(resumeData data: NSData, destination: (NSURL, NSHTTPURLResponse) -> (NSURL)) -> Alamofire.Request {
return Manager.sharedInstance.download(data, destination: destination)
}
}
typealias AF = Alamofire
| This looks a little more succinct:
``` swift
dispatch_async(queue ?? dispatch_get_main_queue(), {
completionHandler(self.request, self.response, responseObject, error)
})
```
| // Alamofire.swift
//
// Copyright (c) 2014 Alamofire (http://alamofire.org)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public struct Alamofire {
// HTTP Method Definitions; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
public enum Method: String {
case OPTIONS = "OPTIONS"
case GET = "GET"
case HEAD = "HEAD"
case POST = "POST"
case PUT = "PUT"
case PATCH = "PATCH"
case DELETE = "DELETE"
case TRACE = "TRACE"
case CONNECT = "CONNECT"
}
public enum ParameterEncoding {
case URL
case JSON(options: NSJSONWritingOptions)
case PropertyList(format: NSPropertyListFormat, options: NSPropertyListWriteOptions)
func encode(request: NSURLRequest, parameters: [String: AnyObject]?) -> (NSURLRequest, NSError?) {
if parameters == nil {
return (request, nil)
}
var mutableRequest: NSMutableURLRequest! = request.mutableCopy() as NSMutableURLRequest
var error: NSError? = nil
switch self {
case .URL:
func query(parameters: [String: AnyObject]) -> String! {
func queryComponents(key: String, value: AnyObject) -> [(String, String)] {
func dictionaryQueryComponents(key: String, dictionary: [String: AnyObject]) -> [(String, String)] {
var components: [(String, String)] = []
for (nestedKey, value) in dictionary {
components += queryComponents("\(key)[\(nestedKey)]", value)
}
return components
}
func arrayQueryComponents(key: String, array: [AnyObject]) -> [(String, String)] {
var components: [(String, String)] = []
for value in array {
components += queryComponents("\(key)[]", value)
}
return components
}
var components: [(String, String)] = []
if let dictionary = value as? [String: AnyObject] {
components += dictionaryQueryComponents(key, dictionary)
} else if let array = value as? [AnyObject] {
components += arrayQueryComponents(key, array)
} else {
components.append(key, "\(value)")
}
return components
}
var components: [(String, String)] = []
for key in sorted(Array(parameters.keys), <) {
let value: AnyObject! = parameters[key]
components += queryComponents(key, value)
}
return join("&", components.map{"\($0)=\($1)"} as [String])
}
func encodesParametersInURL(method: Method) -> Bool {
switch method {
case .GET, .HEAD, .DELETE:
return true
default:
return false
}
}
if encodesParametersInURL(Method.fromRaw(request.HTTPMethod)!) {
let URLComponents = NSURLComponents(URL: mutableRequest.URL, resolvingAgainstBaseURL: false)
URLComponents.query = (URLComponents.query ? URLComponents.query + "&" : "") + query(parameters!)
mutableRequest.URL = URLComponents.URL
} else {
if !mutableRequest.valueForHTTPHeaderField("Content-Type") {
mutableRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
}
mutableRequest.HTTPBody = query(parameters!).dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
}
case .JSON(let options):
let data = NSJSONSerialization.dataWithJSONObject(parameters, options: options, error: &error)
if data {
let charset = CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding))
mutableRequest.setValue("application/json; charset=\(charset)", forHTTPHeaderField: "Content-Type")
mutableRequest.HTTPBody = data
}
case .PropertyList(let (format, options)):
let data = NSPropertyListSerialization.dataWithPropertyList(parameters, format: format, options: options, error: &error)
if data {
let charset = CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
mutableRequest.setValue("application/x-plist; charset=\(charset)", forHTTPHeaderField: "Content-Type")
mutableRequest.HTTPBody = data
}
}
return (mutableRequest, error)
}
}
// MARK: -
class Manager {
class var sharedInstance: Manager {
struct Singleton {
static let instance = Manager()
}
return Singleton.instance
}
let delegate: SessionDelegate
let session: NSURLSession!
let operationQueue: NSOperationQueue = NSOperationQueue()
var automaticallyStartsRequests: Bool = true
lazy var defaultHeaders: [String: String] = {
// Accept-Language HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3
let acceptEncoding: String = "gzip;q=1.0,compress;q=0.5"
// Accept-Language HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
let acceptLanguage: String = {
var components: [String] = []
for (index, languageCode) in enumerate(NSLocale.preferredLanguages() as [String]) {
let q = 1.0 - (Double(index) * 0.1)
components.append("\(languageCode);q=\(q)")
if q <= 0.5 {
break
}
}
return components.reduce("", {$0 == "" ? $1 : "\($0),\($1)"})
}()
// User-Agent Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43
let userAgent: String = {
if let info = NSBundle.mainBundle().infoDictionary {
let executable: AnyObject? = info[kCFBundleExecutableKey]
let bundle: AnyObject? = info[kCFBundleIdentifierKey]
let version: AnyObject? = info[kCFBundleVersionKey]
let os: AnyObject? = NSProcessInfo.processInfo()?.operatingSystemVersionString
var mutableUserAgent = NSMutableString(string: "\(executable!)/\(bundle!) (\(version!); OS \(os!))") as CFMutableString
let transform = NSString(string: "Any-Latin; Latin-ASCII; [:^ASCII:] Remove") as CFString
if CFStringTransform(mutableUserAgent, nil, transform, 0) == 1 {
return mutableUserAgent as NSString
}
}
return "Alamofire"
}()
return ["Accept-Encoding": acceptEncoding,
"Accept-Language": acceptLanguage,
"User-Agent": userAgent]
}()
required init(configuration: NSURLSessionConfiguration! = nil) {
self.delegate = SessionDelegate()
self.session = NSURLSession(configuration: configuration, delegate: self.delegate, delegateQueue: self.operationQueue)
}
deinit {
self.session.invalidateAndCancel()
}
// MARK: -
func request(request: NSURLRequest) -> Request {
var mutableRequest: NSMutableURLRequest! = request.mutableCopy() as NSMutableURLRequest
for (field, value) in self.defaultHeaders {
if !mutableRequest.valueForHTTPHeaderField(field){
mutableRequest.setValue(value, forHTTPHeaderField: field)
}
}
var dataTask: NSURLSessionDataTask?
dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
dataTask = self.session.dataTaskWithRequest(mutableRequest)
}
let request = Request(session: self.session, task: dataTask!)
self.delegate[request.delegate.task] = request.delegate
request.resume()
return request
}
class SessionDelegate: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate {
private var subdelegates: [Int: Request.TaskDelegate]
private subscript(task: NSURLSessionTask) -> Request.TaskDelegate? {
get {
return self.subdelegates[task.taskIdentifier]
}
set(newValue) {
self.subdelegates[task.taskIdentifier] = newValue
}
}
var sessionDidBecomeInvalidWithError: ((NSURLSession!, NSError!) -> Void)?
var sessionDidFinishEventsForBackgroundURLSession: ((NSURLSession!) -> Void)?
var sessionDidReceiveChallenge: ((NSURLSession!, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential!))?
var taskWillPerformHTTPRedirection: ((NSURLSession!, NSURLSessionTask!, NSHTTPURLResponse!, NSURLRequest!) -> (NSURLRequest!))?
var taskDidReceiveChallenge: ((NSURLSession!, NSURLSessionTask!, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
var taskDidSendBodyData: ((NSURLSession!, NSURLSessionTask!, Int64, Int64, Int64) -> Void)?
var taskNeedNewBodyStream: ((NSURLSession!, NSURLSessionTask!) -> (NSInputStream!))?
var dataTaskDidReceiveResponse: ((NSURLSession!, NSURLSessionDataTask!, NSURLResponse!) -> (NSURLSessionResponseDisposition))?
var dataTaskDidBecomeDownloadTask: ((NSURLSession!, NSURLSessionDataTask!) -> Void)?
var dataTaskDidReceiveData: ((NSURLSession!, NSURLSessionDataTask!, NSData!) -> Void)?
var dataTaskWillCacheResponse: ((NSURLSession!, NSURLSessionDataTask!, NSCachedURLResponse!) -> (NSCachedURLResponse))?
var downloadTaskDidFinishDownloadingToURL: ((NSURLSession!, NSURLSessionDownloadTask!, NSURL) -> (NSURL))?
var downloadTaskDidWriteData: ((NSURLSession!, NSURLSessionDownloadTask!, Int64, Int64, Int64) -> Void)?
var downloadTaskDidResumeAtOffset: ((NSURLSession!, NSURLSessionDownloadTask!, Int64, Int64) -> Void)?
required override init() {
self.subdelegates = Dictionary()
super.init()
}
// MARK: NSURLSessionDelegate
func URLSession(session: NSURLSession!, didBecomeInvalidWithError error: NSError!) {
self.sessionDidBecomeInvalidWithError?(session, error)
}
func URLSession(session: NSURLSession!, didReceiveChallenge challenge: NSURLAuthenticationChallenge!, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)!) {
if self.sessionDidReceiveChallenge != nil {
completionHandler(self.sessionDidReceiveChallenge!(session, challenge))
} else {
completionHandler(.PerformDefaultHandling, nil)
}
}
func URLSessionDidFinishEventsForBackgroundURLSession(session: NSURLSession!) {
self.sessionDidFinishEventsForBackgroundURLSession?(session)
}
// MARK: NSURLSessionTaskDelegate
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, willPerformHTTPRedirection response: NSHTTPURLResponse!, newRequest request: NSURLRequest!, completionHandler: ((NSURLRequest!) -> Void)!) {
var redirectRequest = request
if self.taskWillPerformHTTPRedirection != nil {
redirectRequest = self.taskWillPerformHTTPRedirection!(session, task, response, request)
}
completionHandler(redirectRequest)
}
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didReceiveChallenge challenge: NSURLAuthenticationChallenge!, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)!) {
if let delegate = self[task] {
delegate.URLSession(session, task: task, didReceiveChallenge: challenge, completionHandler: completionHandler)
} else {
self.URLSession(session, didReceiveChallenge: challenge, completionHandler: completionHandler)
}
}
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, needNewBodyStream completionHandler: ((NSInputStream!) -> Void)!) {
if let delegate = self[task] {
delegate.URLSession(session, task: task, needNewBodyStream: completionHandler)
}
}
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
if let delegate = self[task] as? Request.UploadTaskDelegate {
delegate.URLSession(session, task: task, didSendBodyData: bytesSent, totalBytesSent: totalBytesSent, totalBytesExpectedToSend: totalBytesExpectedToSend)
}
}
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didCompleteWithError error: NSError!) {
if let delegate = self[task] {
delegate.URLSession(session, task: task, didCompleteWithError: error)
}
}
// MARK: NSURLSessionDataDelegate
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didReceiveResponse response: NSURLResponse!, completionHandler: ((NSURLSessionResponseDisposition) -> Void)!) {
var disposition: NSURLSessionResponseDisposition = .Allow
if self.dataTaskDidReceiveResponse != nil {
disposition = self.dataTaskDidReceiveResponse!(session, dataTask, response)
}
completionHandler(disposition)
}
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask!) {
let downloadDelegate = Request.DownloadTaskDelegate(task: downloadTask)
self[downloadTask] = downloadDelegate
}
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didReceiveData data: NSData!) {
if let delegate = self[dataTask] as? Request.DataTaskDelegate {
delegate.URLSession(session, dataTask: dataTask, didReceiveData: data)
}
self.dataTaskDidReceiveData?(session, dataTask, data)
}
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, willCacheResponse proposedResponse: NSCachedURLResponse!, completionHandler: ((NSCachedURLResponse!) -> Void)!) {
var cachedResponse = proposedResponse
if self.dataTaskWillCacheResponse != nil {
cachedResponse = self.dataTaskWillCacheResponse!(session, dataTask, proposedResponse)
}
completionHandler(cachedResponse)
}
// MARK: NSURLSessionDownloadDelegate
func URLSession(session: NSURLSession!, downloadTask: NSURLSessionDownloadTask!, didFinishDownloadingToURL location: NSURL!) {
if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
delegate.URLSession(session, downloadTask: downloadTask, didFinishDownloadingToURL: location)
}
self.downloadTaskDidFinishDownloadingToURL?(session, downloadTask, location)
}
func URLSession(session: NSURLSession!, downloadTask: NSURLSessionDownloadTask!, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
delegate.URLSession(session, downloadTask: downloadTask, didWriteData: bytesWritten, totalBytesWritten: totalBytesWritten, totalBytesExpectedToWrite: totalBytesExpectedToWrite)
}
self.downloadTaskDidWriteData?(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
}
func URLSession(session: NSURLSession!, downloadTask: NSURLSessionDownloadTask!, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
delegate.URLSession(session, downloadTask: downloadTask, didResumeAtOffset: fileOffset, expectedTotalBytes: expectedTotalBytes)
}
self.downloadTaskDidResumeAtOffset?(session, downloadTask, fileOffset, expectedTotalBytes)
}
// MARK: NSObject
override func respondsToSelector(selector: Selector) -> Bool {
switch selector {
case "URLSession:didBecomeInvalidWithError:":
return (self.sessionDidBecomeInvalidWithError != nil)
case "URLSession:didReceiveChallenge:completionHandler:":
return (self.sessionDidReceiveChallenge != nil)
case "URLSessionDidFinishEventsForBackgroundURLSession:":
return (self.sessionDidFinishEventsForBackgroundURLSession != nil)
case "URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:":
return (self.taskWillPerformHTTPRedirection != nil)
case "URLSession:dataTask:didReceiveResponse:completionHandler:":
return (self.dataTaskDidReceiveResponse != nil)
case "URLSession:dataTask:willCacheResponse:completionHandler:":
return (self.dataTaskWillCacheResponse != nil)
default:
return self.dynamicType.instancesRespondToSelector(selector)
}
}
}
}
// MARK: -
class Request {
private let delegate: TaskDelegate
private var session: NSURLSession
private var task: NSURLSessionTask { return self.delegate.task }
var request: NSURLRequest! { return self.task.originalRequest }
var response: NSHTTPURLResponse! { return self.task.response as? NSHTTPURLResponse }
var progress: NSProgress? { return self.delegate.progress }
private init(session: NSURLSession, task: NSURLSessionTask) {
self.session = session
if task is NSURLSessionUploadTask {
self.delegate = UploadTaskDelegate(task: task)
} else if task is NSURLSessionDownloadTask {
self.delegate = DownloadTaskDelegate(task: task)
} else if task is NSURLSessionDataTask {
self.delegate = DataTaskDelegate(task: task)
} else {
self.delegate = TaskDelegate(task: task)
}
}
// MARK: Authentication
func authenticate(HTTPBasic user: String, password: String) -> Self {
let credential = NSURLCredential(user: user, password: password, persistence: .ForSession)
let protectionSpace = NSURLProtectionSpace(host: self.request.URL.host, port: 0, `protocol`: self.request.URL.scheme, realm: nil, authenticationMethod: NSURLAuthenticationMethodHTTPBasic)
return authenticate(usingCredential: credential, forProtectionSpace: protectionSpace)
}
func authenticate(usingCredential credential: NSURLCredential, forProtectionSpace protectionSpace: NSURLProtectionSpace) -> Self {
self.session.configuration.URLCredentialStorage.setCredential(credential, forProtectionSpace: protectionSpace)
return self
}
// MARK: Progress
func progress(closure: ((Int64, Int64, Int64) -> Void)? = nil) -> Self {
if let uploadDelegate = self.delegate as? UploadTaskDelegate {
uploadDelegate.uploadProgress = closure
} else if let downloadDelegate = self.delegate as? DownloadTaskDelegate {
downloadDelegate.downloadProgress = closure
}
return self
}
// MARK: Response
func response(completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
return response({ (request, response, data, error) in
return (data, error)
}, completionHandler: completionHandler)
}
func response(priority: Int = DISPATCH_QUEUE_PRIORITY_DEFAULT, queue: dispatch_queue_t? = nil, serializer: (NSURLRequest, NSHTTPURLResponse?, NSData?, NSError?) -> (AnyObject?, NSError?), completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
dispatch_async(self.delegate.queue, {
dispatch_async(dispatch_get_global_queue(priority, 0), {
let (responseObject: AnyObject?, error: NSError?) = serializer(self.request, self.response, self.delegate.data, self.delegate.error)
dispatch_async(queue ?? dispatch_get_main_queue(), {
completionHandler(self.request, self.response, responseObject, error)
})
})
})
return self
}
func suspend() {
self.task.suspend()
}
func resume() {
self.task.resume()
}
func cancel() {
if let downloadDelegate = self.delegate as? DownloadTaskDelegate {
downloadDelegate.downloadTask.cancelByProducingResumeData { (data) in
downloadDelegate.resumeData = data
}
} else {
self.task.cancel()
}
}
private class TaskDelegate: NSObject, NSURLSessionTaskDelegate {
let task: NSURLSessionTask
let queue: dispatch_queue_t?
let progress: NSProgress
var data: NSData! { return nil }
private(set) var error: NSError?
var taskWillPerformHTTPRedirection: ((NSURLSession!, NSURLSessionTask!, NSHTTPURLResponse!, NSURLRequest!) -> (NSURLRequest!))?
var taskDidReceiveChallenge: ((NSURLSession!, NSURLSessionTask!, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
var taskDidSendBodyData: ((NSURLSession!, NSURLSessionTask!, Int64, Int64, Int64) -> Void)?
var taskNeedNewBodyStream: ((NSURLSession!, NSURLSessionTask!) -> (NSInputStream!))?
init(task: NSURLSessionTask) {
self.task = task
self.progress = NSProgress(totalUnitCount: 0)
let label: String = "com.alamofire.task-\(task.taskIdentifier)"
let queue = dispatch_queue_create((label as NSString).UTF8String, DISPATCH_QUEUE_SERIAL)
dispatch_suspend(queue)
self.queue = queue
}
// MARK: NSURLSessionTaskDelegate
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, willPerformHTTPRedirection response: NSHTTPURLResponse!, newRequest request: NSURLRequest!, completionHandler: ((NSURLRequest!) -> Void)!) {
var redirectRequest = request
if self.taskWillPerformHTTPRedirection != nil {
redirectRequest = self.taskWillPerformHTTPRedirection!(session, task, response, request)
}
completionHandler(redirectRequest)
}
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didReceiveChallenge challenge: NSURLAuthenticationChallenge!, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)!) {
var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling
var credential: NSURLCredential?
if self.taskDidReceiveChallenge != nil {
(disposition, credential) = self.taskDidReceiveChallenge!(session, task, challenge)
} else {
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
// TODO: Incorporate Trust Evaluation & TLS Chain Validation
credential = NSURLCredential(forTrust: challenge.protectionSpace.serverTrust)
disposition = .UseCredential
}
}
completionHandler(disposition, credential)
}
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, needNewBodyStream completionHandler: ((NSInputStream!) -> Void)!) {
var bodyStream: NSInputStream?
if self.taskNeedNewBodyStream != nil {
bodyStream = self.taskNeedNewBodyStream!(session, task)
}
completionHandler(bodyStream)
}
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didCompleteWithError error: NSError!) {
dispatch_resume(self.queue)
}
}
private class DataTaskDelegate: TaskDelegate, NSURLSessionDataDelegate {
var dataTask: NSURLSessionDataTask! { return self.task as NSURLSessionDataTask }
private var mutableData: NSMutableData
override var data: NSData! {
return self.mutableData
}
var dataTaskDidReceiveResponse: ((NSURLSession!, NSURLSessionDataTask!, NSURLResponse!) -> (NSURLSessionResponseDisposition))?
var dataTaskDidBecomeDownloadTask: ((NSURLSession!, NSURLSessionDataTask!) -> Void)?
var dataTaskDidReceiveData: ((NSURLSession!, NSURLSessionDataTask!, NSData!) -> Void)?
var dataTaskWillCacheResponse: ((NSURLSession!, NSURLSessionDataTask!, NSCachedURLResponse!) -> (NSCachedURLResponse))?
override init(task: NSURLSessionTask) {
self.mutableData = NSMutableData()
super.init(task: task)
}
// MARK: NSURLSessionDataDelegate
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didReceiveResponse response: NSURLResponse!, completionHandler: ((NSURLSessionResponseDisposition) -> Void)!) {
var disposition: NSURLSessionResponseDisposition = .Allow
if self.dataTaskDidReceiveResponse != nil {
disposition = self.dataTaskDidReceiveResponse!(session, dataTask, response)
}
completionHandler(disposition)
}
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask!) {
self.dataTaskDidBecomeDownloadTask?(session, dataTask)
}
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didReceiveData data: NSData!) {
self.dataTaskDidReceiveData?(session, dataTask, data)
self.mutableData.appendData(data)
}
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, willCacheResponse proposedResponse: NSCachedURLResponse!, completionHandler: ((NSCachedURLResponse!) -> Void)!) {
var cachedResponse = proposedResponse
if self.dataTaskWillCacheResponse != nil {
cachedResponse = self.dataTaskWillCacheResponse!(session, dataTask, proposedResponse)
}
completionHandler(cachedResponse)
}
}
}
}
// MARK: - Upload
extension Alamofire.Manager {
private enum Uploadable {
case Data(NSURLRequest, NSData)
case File(NSURLRequest, NSURL)
case Stream(NSURLRequest, NSInputStream)
}
private func upload(uploadable: Uploadable) -> Alamofire.Request {
var uploadTask: NSURLSessionUploadTask!
var stream: NSInputStream?
switch uploadable {
case .Data(let request, let data):
uploadTask = self.session.uploadTaskWithRequest(request, fromData: data)
case .File(let request, let fileURL):
uploadTask = self.session.uploadTaskWithRequest(request, fromFile: fileURL)
case .Stream(let request, var stream):
uploadTask = self.session.uploadTaskWithStreamedRequest(request)
}
let request = Alamofire.Request(session: self.session, task: uploadTask)
if stream != nil {
request.delegate.taskNeedNewBodyStream = { _, _ in
return stream
}
}
self.delegate[request.delegate.task] = request.delegate
if self.automaticallyStartsRequests {
request.resume()
}
return request
}
// MARK: File
func upload(request: NSURLRequest, file: NSURL) -> Alamofire.Request {
return upload(.File(request, file))
}
// MARK: Data
func upload(request: NSURLRequest, data: NSData) -> Alamofire.Request {
return upload(.Data(request, data))
}
// MARK: Stream
func upload(request: NSURLRequest, stream: NSInputStream) -> Alamofire.Request {
return upload(.Stream(request, stream))
}
}
extension Alamofire.Request {
private class UploadTaskDelegate: DataTaskDelegate {
var uploadTask: NSURLSessionUploadTask! { return self.task as NSURLSessionUploadTask }
var uploadProgress: ((Int64, Int64, Int64) -> Void)!
// MARK: NSURLSessionTaskDelegate
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
if self.uploadProgress {
self.uploadProgress(bytesSent, totalBytesSent, totalBytesExpectedToSend)
}
self.progress.totalUnitCount = totalBytesExpectedToSend
self.progress.completedUnitCount = totalBytesSent
}
}
}
// MARK: - Download
extension Alamofire.Manager {
private enum Downloadable {
case Request(NSURLRequest)
case ResumeData(NSData)
}
private func download(downloadable: Downloadable, destination: (NSURL, NSHTTPURLResponse) -> (NSURL)) -> Alamofire.Request {
var downloadTask: NSURLSessionDownloadTask!
switch downloadable {
case .Request(let request):
downloadTask = self.session.downloadTaskWithRequest(request)
case .ResumeData(let resumeData):
downloadTask = self.session.downloadTaskWithResumeData(resumeData)
}
let request = Alamofire.Request(session: self.session, task: downloadTask)
if let downloadDelegate = request.delegate as? Alamofire.Request.DownloadTaskDelegate {
downloadDelegate.downloadTaskDidFinishDownloadingToURL = { (session, downloadTask, URL) in
return destination(URL, downloadTask.response as NSHTTPURLResponse)
}
}
self.delegate[request.delegate.task] = request.delegate
if self.automaticallyStartsRequests {
request.resume()
}
return request
}
// MARK: Request
func download(request: NSURLRequest, destination: (NSURL, NSHTTPURLResponse) -> (NSURL)) -> Alamofire.Request {
return download(.Request(request), destination: destination)
}
// MARK: Resume Data
func download(resumeData: NSData, destination: (NSURL, NSHTTPURLResponse) -> (NSURL)) -> Alamofire.Request {
return download(.ResumeData(resumeData), destination: destination)
}
}
extension Alamofire.Request {
class func suggestedDownloadDestination(directory: NSSearchPathDirectory = .DocumentDirectory, domain: NSSearchPathDomainMask = .UserDomainMask) -> (NSURL, NSHTTPURLResponse) -> (NSURL) {
return { (temporaryURL, response) -> (NSURL) in
if let directoryURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as? NSURL {
return directoryURL.URLByAppendingPathComponent(response.suggestedFilename)
}
return temporaryURL
}
}
private class DownloadTaskDelegate: TaskDelegate, NSURLSessionDownloadDelegate {
var downloadTask: NSURLSessionDownloadTask! { return self.task as NSURLSessionDownloadTask }
var downloadProgress: ((Int64, Int64, Int64) -> Void)?
var resumeData: NSData!
override var data: NSData! { return self.resumeData }
var downloadTaskDidFinishDownloadingToURL: ((NSURLSession!, NSURLSessionDownloadTask!, NSURL) -> (NSURL))?
var downloadTaskDidWriteData: ((NSURLSession!, NSURLSessionDownloadTask!, Int64, Int64, Int64) -> Void)?
var downloadTaskDidResumeAtOffset: ((NSURLSession!, NSURLSessionDownloadTask!, Int64, Int64) -> Void)?
// MARK: NSURLSessionDownloadDelegate
func URLSession(session: NSURLSession!, downloadTask: NSURLSessionDownloadTask!, didFinishDownloadingToURL location: NSURL!) {
if self.downloadTaskDidFinishDownloadingToURL != nil {
let destination = self.downloadTaskDidFinishDownloadingToURL!(session, downloadTask, location)
var fileManagerError: NSError?
NSFileManager.defaultManager().moveItemAtURL(location, toURL: destination, error: &fileManagerError)
// TODO: NSNotification on failure
}
}
func URLSession(session: NSURLSession!, downloadTask: NSURLSessionDownloadTask!, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
self.downloadTaskDidWriteData?(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
self.downloadProgress?(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
self.progress.totalUnitCount = totalBytesExpectedToWrite
self.progress.completedUnitCount = totalBytesWritten
}
func URLSession(session: NSURLSession!, downloadTask: NSURLSessionDownloadTask!, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
self.downloadTaskDidResumeAtOffset?(session, downloadTask, fileOffset, expectedTotalBytes)
self.progress.totalUnitCount = expectedTotalBytes
self.progress.completedUnitCount = fileOffset
}
}
}
// MARK: - Printable
extension Alamofire.Request: Printable {
var description: String {
var description = "\(self.request.HTTPMethod) \(self.request.URL)"
if self.response {
description += " (\(self.response?.statusCode))"
}
return description
}
}
extension Alamofire.Request: DebugPrintable {
func cURLRepresentation() -> String {
var components: [String] = ["$ curl -i"]
let URL = self.request.URL!
if self.request.HTTPMethod != "GET" {
components.append("-X \(self.request.HTTPMethod)")
}
if let credentialStorage = self.session.configuration.URLCredentialStorage {
let protectionSpace = NSURLProtectionSpace(host: URL.host, port: URL.port ? URL.port : 0, `protocol`: URL.scheme, realm: URL.host, authenticationMethod: NSURLAuthenticationMethodHTTPBasic)
if let credentials = credentialStorage.credentialsForProtectionSpace(protectionSpace)?.values.array {
if !credentials.isEmpty {
if let credential = credentials[0] as? NSURLCredential {
components.append("-u \(credential.user):\(credential.password)")
}
}
}
}
if let cookieStorage = self.session.configuration.HTTPCookieStorage {
if let cookies = cookieStorage.cookiesForURL(URL) as? [NSHTTPCookie] {
if !cookies.isEmpty {
let string = cookies.reduce(""){ $0 + "\($1.name)=\($1.value);" }
components.append("-b \"\(string.substringToIndex(string.endIndex.predecessor()))\"")
}
}
}
for (field, value) in self.request.allHTTPHeaderFields {
switch field {
case "Cookie":
continue
default:
components.append("-H \"\(field): \(value)\"")
}
}
if let HTTPBody = self.request.HTTPBody {
components.append("-d \"\(NSString(data: HTTPBody, encoding: NSUTF8StringEncoding))\"")
}
// TODO: -T arguments for files
components.append("\"\(URL.absoluteString)\"")
return join(" \\\n\t", components)
}
var debugDescription: String {
return self.cURLRepresentation()
}
}
// MARK: - Response Serializers
// MARK: String
extension Alamofire.Request {
class func stringResponseSerializer(encoding: NSStringEncoding = NSUTF8StringEncoding) -> (NSURLRequest, NSHTTPURLResponse?, NSData?, NSError?) -> (AnyObject?, NSError?) {
return { (_, _, data, error) in
let string = NSString(data: data, encoding: encoding)
return (string, error)
}
}
func responseString(completionHandler: (NSURLRequest, NSHTTPURLResponse?, String?, NSError?) -> Void) -> Self {
return responseString(completionHandler: completionHandler)
}
func responseString(encoding: NSStringEncoding = NSUTF8StringEncoding, completionHandler: (NSURLRequest, NSHTTPURLResponse?, String?, NSError?) -> Void) -> Self {
return response(serializer: Alamofire.Request.stringResponseSerializer(encoding: encoding), completionHandler: { request, response, string, error in
completionHandler(request, response, string as? String, error)
})
}
}
// MARK: JSON
extension Alamofire.Request {
class func JSONResponseSerializer(options: NSJSONReadingOptions = .AllowFragments) -> (NSURLRequest, NSHTTPURLResponse?, NSData?, NSError?) -> (AnyObject?, NSError?) {
return { (request, response, data, error) in
var serializationError: NSError?
let JSON: AnyObject! = NSJSONSerialization.JSONObjectWithData(data, options: options, error: &serializationError)
return (JSON, serializationError)
}
}
func responseJSON(completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
return responseJSON(completionHandler: completionHandler)
}
func responseJSON(options: NSJSONReadingOptions = .AllowFragments, completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
return response(serializer: Alamofire.Request.JSONResponseSerializer(options: options), completionHandler: { (request, response, JSON, error) in
completionHandler(request, response, JSON, error)
})
}
}
// MARK: Property List
extension Alamofire.Request {
class func propertyListResponseSerializer(options: NSPropertyListReadOptions = 0) -> (NSURLRequest, NSHTTPURLResponse?, NSData?, NSError?) -> (AnyObject?, NSError?) {
return { (request, response, data, error) in
var propertyListSerializationError: NSError?
let plist: AnyObject! = NSPropertyListSerialization.propertyListWithData(data, options: options, format: nil, error: &propertyListSerializationError)
return (plist, propertyListSerializationError)
}
}
func responsePropertyList(completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
return responsePropertyList(completionHandler: completionHandler)
}
func responsePropertyList(options: NSPropertyListReadOptions = 0, completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
return response(serializer: Alamofire.Request.propertyListResponseSerializer(options: options), completionHandler: { (request, response, plist, error) in
completionHandler(request, response, plist, error)
})
}
}
// MARK: - Convenience
extension Alamofire {
private static func URLRequest(method: Method, _ URL: String) -> NSURLRequest {
let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: URL))
mutableURLRequest.HTTPMethod = method.toRaw()
return mutableURLRequest
}
// MARK: Request
static func request(method: Method, _ URL: String, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL) -> Request {
return Manager.sharedInstance.request(encoding.encode(URLRequest(method, URL), parameters: parameters).0)
}
// MARK: Upload
static func upload(method: Method, _ URL: String, file: NSURL) -> Alamofire.Request {
return Manager.sharedInstance.upload(URLRequest(method, URL), file: file)
}
static func upload(method: Method, _ URL: String, data: NSData) -> Alamofire.Request {
return Manager.sharedInstance.upload(URLRequest(method, URL), data: data)
}
static func upload(method: Method, _ URL: String, stream: NSInputStream) -> Alamofire.Request {
return Manager.sharedInstance.upload(URLRequest(method, URL), stream: stream)
}
// MARK: Download
static func download(method: Method, _ URL: String, destination: (NSURL, NSHTTPURLResponse) -> (NSURL)) -> Alamofire.Request {
return Manager.sharedInstance.download(URLRequest(method, URL), destination: destination)
}
static func download(resumeData data: NSData, destination: (NSURL, NSHTTPURLResponse) -> (NSURL)) -> Alamofire.Request {
return Manager.sharedInstance.download(data, destination: destination)
}
}
typealias AF = Alamofire
| @@ -467,7 +467,7 @@ public struct Alamofire {
dispatch_async(dispatch_get_global_queue(priority, 0), {
let (responseObject: AnyObject?, error: NSError?) = serializer(self.request, self.response, self.delegate.data, self.delegate.error)
- dispatch_async(queue ? queue : dispatch_get_main_queue(), {
+ dispatch_async((queue != nil) ? queue : dispatch_get_main_queue(), { | Source/Alamofire.swift | 0 | Swift | 0.857 | suggestion | 178 | 967 | 967 | false | Update to support the Xcode 6 Beta5 changes to Swift | 24 | Alamofire/Alamofire | 41,690 | Swift | camjknight | troypayne |
// DownloadTests.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Alamofire
import Foundation
import XCTest
class DownloadResponseTestCase: BaseTestCase {
// MARK: - Properties
let searchPathDirectory: NSSearchPathDirectory = .CachesDirectory
let searchPathDomain: NSSearchPathDomainMask = .UserDomainMask
// MARK: - Tests
func testDownloadRequest() {
// Given
let numberOfLines = 100
let URLString = "http://httpbin.org/stream/\(numberOfLines)"
let destination = Alamofire.Request.suggestedDownloadDestination(directory: searchPathDirectory, domain: searchPathDomain)
let expectation = expectationWithDescription("Download request should download data to file: \(URLString)")
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var error: NSError?
// When
Alamofire.download(.GET, URLString, destination)
.response { responseRequest, responseResponse, _, responseError in
request = responseRequest
response = responseResponse
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertNil(error, "error should be nil")
let fileManager = NSFileManager.defaultManager()
let directory = fileManager.URLsForDirectory(self.searchPathDirectory, inDomains: self.searchPathDomain)[0] as! NSURL
var fileManagerError: NSError?
if let contents = fileManager.contentsOfDirectoryAtURL(directory, includingPropertiesForKeys: nil, options: .SkipsHiddenFiles, error: &fileManagerError) {
XCTAssertNil(fileManagerError, "fileManagerError should be nil")
#if os(iOS)
let suggestedFilename = "\(numberOfLines)"
#elseif os(OSX)
let suggestedFilename = "\(numberOfLines).json"
#endif
let predicate = NSPredicate(format: "lastPathComponent = '\(suggestedFilename)'")
let filteredContents = (contents as NSArray).filteredArrayUsingPredicate(predicate)
XCTAssertEqual(filteredContents.count, 1, "should have one file in Documents")
if let file = filteredContents.first as? NSURL {
XCTAssertEqual(file.lastPathComponent ?? "", "\(suggestedFilename)", "filename should be \(suggestedFilename)")
if let data = NSData(contentsOfURL: file) {
XCTAssertGreaterThan(data.length, 0, "data length should be non-zero")
} else {
XCTFail("data should exist for contents of URL")
}
fileManager.removeItemAtURL(file, error: nil)
} else {
XCTFail("file should not be nil")
}
} else {
XCTFail("contents should not be nil")
}
}
func testDownloadRequestWithProgress2() {
// Given
let randomBytes = 4 * 1024 * 1024
let URLString = "http://httpbin.org/bytes/\(randomBytes)"
let fileManager = NSFileManager.defaultManager()
let directory = fileManager.URLsForDirectory(self.searchPathDirectory, inDomains: self.searchPathDomain)[0] as! NSURL
let filename = "test_download_data"
let fileURL = directory.URLByAppendingPathComponent(filename)
let expectation = expectationWithDescription("Bytes download progress should be reported: \(URLString)")
var byteValues: [(bytes: Int64, totalBytes: Int64, totalBytesExpected: Int64)] = []
var progressValues: [(completedUnitCount: Int64, totalUnitCount: Int64)] = []
var responseRequest: NSURLRequest?
var responseResponse: NSHTTPURLResponse?
var responseData: AnyObject?
var responseError: NSError?
// When
let download = Alamofire.download(.GET, URLString) { _, _ in
return fileURL
}
download.progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
let bytes = (bytes: bytesRead, totalBytes: totalBytesRead, totalBytesExpected: totalBytesExpectedToRead)
byteValues.append(bytes)
let progress = (completedUnitCount: download.progress.completedUnitCount, totalUnitCount: download.progress.totalUnitCount)
progressValues.append(progress)
}
download.response { request, response, data, error in
responseRequest = request
responseResponse = response
responseData = data
responseError = error
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(responseRequest, "response request should not be nil")
XCTAssertNotNil(responseResponse, "response response should not be nil")
XCTAssertNil(responseData, "response data should be nil")
XCTAssertNil(responseError, "response error should be nil")
XCTAssertEqual(byteValues.count, progressValues.count, "byteValues count should equal progressValues count")
if byteValues.count == progressValues.count {
for index in 0..<byteValues.count {
let byteValue = byteValues[index]
let progressValue = progressValues[index]
XCTAssertGreaterThan(byteValue.bytes, 0, "reported bytes should always be greater than 0")
XCTAssertEqual(byteValue.totalBytes, progressValue.completedUnitCount, "total bytes should be equal to completed unit count")
XCTAssertEqual(byteValue.totalBytesExpected, progressValue.totalUnitCount, "total bytes expected should be equal to total unit count")
}
}
if let lastByteValue = byteValues.last,
lastProgressValue = progressValues.last
{
let byteValueFractionalCompletion = Double(lastByteValue.totalBytes) / Double(lastByteValue.totalBytesExpected)
let progressValueFractionalCompletion = Double(lastProgressValue.0) / Double(lastProgressValue.1)
XCTAssertEqual(byteValueFractionalCompletion, 1.0, "byte value fractional completion should equal 1.0")
XCTAssertEqual(progressValueFractionalCompletion, 1.0, "progress value fractional completion should equal 1.0")
} else {
XCTFail("last item in bytesValues and progressValues should not be nil")
}
var removalError: NSError?
fileManager.removeItemAtURL(fileURL, error: &removalError)
XCTAssertNil(removalError, "removal error should be nil")
}
}
| I'd get more descriptive with the name.
| // DownloadTests.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Alamofire
import Foundation
import XCTest
class DownloadResponseTestCase: BaseTestCase {
// MARK: - Properties
let searchPathDirectory: NSSearchPathDirectory = .CachesDirectory
let searchPathDomain: NSSearchPathDomainMask = .UserDomainMask
// MARK: - Tests
func testDownloadRequest() {
// Given
let numberOfLines = 100
let URLString = "http://httpbin.org/stream/\(numberOfLines)"
let destination = Alamofire.Request.suggestedDownloadDestination(directory: searchPathDirectory, domain: searchPathDomain)
let expectation = expectationWithDescription("Download request should download data to file: \(URLString)")
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var error: NSError?
// When
Alamofire.download(.GET, URLString, destination)
.response { responseRequest, responseResponse, _, responseError in
request = responseRequest
response = responseResponse
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertNil(error, "error should be nil")
let fileManager = NSFileManager.defaultManager()
let directory = fileManager.URLsForDirectory(self.searchPathDirectory, inDomains: self.searchPathDomain)[0] as! NSURL
var fileManagerError: NSError?
if let contents = fileManager.contentsOfDirectoryAtURL(directory, includingPropertiesForKeys: nil, options: .SkipsHiddenFiles, error: &fileManagerError) {
XCTAssertNil(fileManagerError, "fileManagerError should be nil")
#if os(iOS)
let suggestedFilename = "\(numberOfLines)"
#elseif os(OSX)
let suggestedFilename = "\(numberOfLines).json"
#endif
let predicate = NSPredicate(format: "lastPathComponent = '\(suggestedFilename)'")
let filteredContents = (contents as NSArray).filteredArrayUsingPredicate(predicate)
XCTAssertEqual(filteredContents.count, 1, "should have one file in Documents")
if let file = filteredContents.first as? NSURL {
XCTAssertEqual(file.lastPathComponent ?? "", "\(suggestedFilename)", "filename should be \(suggestedFilename)")
if let data = NSData(contentsOfURL: file) {
XCTAssertGreaterThan(data.length, 0, "data length should be non-zero")
} else {
XCTFail("data should exist for contents of URL")
}
fileManager.removeItemAtURL(file, error: nil)
} else {
XCTFail("file should not be nil")
}
} else {
XCTFail("contents should not be nil")
}
}
func testDownloadRequestWithProgress() {
// Given
let randomBytes = 4 * 1024 * 1024
let URLString = "http://httpbin.org/bytes/\(randomBytes)"
let fileManager = NSFileManager.defaultManager()
let directory = fileManager.URLsForDirectory(self.searchPathDirectory, inDomains: self.searchPathDomain)[0] as! NSURL
let filename = "test_download_data"
let fileURL = directory.URLByAppendingPathComponent(filename)
let expectation = expectationWithDescription("Bytes download progress should be reported: \(URLString)")
var byteValues: [(bytes: Int64, totalBytes: Int64, totalBytesExpected: Int64)] = []
var progressValues: [(completedUnitCount: Int64, totalUnitCount: Int64)] = []
var responseRequest: NSURLRequest?
var responseResponse: NSHTTPURLResponse?
var responseData: AnyObject?
var responseError: NSError?
// When
let download = Alamofire.download(.GET, URLString) { _, _ in
return fileURL
}
download.progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
let bytes = (bytes: bytesRead, totalBytes: totalBytesRead, totalBytesExpected: totalBytesExpectedToRead)
byteValues.append(bytes)
let progress = (completedUnitCount: download.progress.completedUnitCount, totalUnitCount: download.progress.totalUnitCount)
progressValues.append(progress)
}
download.response { request, response, data, error in
responseRequest = request
responseResponse = response
responseData = data
responseError = error
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(responseRequest, "response request should not be nil")
XCTAssertNotNil(responseResponse, "response response should not be nil")
XCTAssertNil(responseData, "response data should be nil")
XCTAssertNil(responseError, "response error should be nil")
XCTAssertEqual(byteValues.count, progressValues.count, "byteValues count should equal progressValues count")
if byteValues.count == progressValues.count {
for index in 0..<byteValues.count {
let byteValue = byteValues[index]
let progressValue = progressValues[index]
XCTAssertGreaterThan(byteValue.bytes, 0, "reported bytes should always be greater than 0")
XCTAssertEqual(byteValue.totalBytes, progressValue.completedUnitCount, "total bytes should be equal to completed unit count")
XCTAssertEqual(byteValue.totalBytesExpected, progressValue.totalUnitCount, "total bytes expected should be equal to total unit count")
}
}
if let lastByteValue = byteValues.last,
lastProgressValue = progressValues.last
{
let byteValueFractionalCompletion = Double(lastByteValue.totalBytes) / Double(lastByteValue.totalBytesExpected)
let progressValueFractionalCompletion = Double(lastProgressValue.0) / Double(lastProgressValue.1)
XCTAssertEqual(byteValueFractionalCompletion, 1.0, "byte value fractional completion should equal 1.0")
XCTAssertEqual(progressValueFractionalCompletion, 1.0, "progress value fractional completion should equal 1.0")
} else {
XCTFail("last item in bytesValues and progressValues should not be nil")
}
var removalError: NSError?
fileManager.removeItemAtURL(fileURL, error: &removalError)
XCTAssertNil(removalError, "removal error should be nil")
}
}
| @@ -97,27 +97,41 @@ class DownloadResponseTestCase: BaseTestCase {
}
}
- func testDownloadRequestWithProgress() {
+ func testDownloadRequestWithProgress2() { | Tests/DownloadTests.swift | 0 | Swift | 0.071 | suggestion | 40 | 177 | 177 | false | Created more robust data, upload and download progress tests | 494 | Alamofire/Alamofire | 41,690 | Swift | kcharwood | cnoon |
// DownloadTests.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Alamofire
import Foundation
import XCTest
class DownloadResponseTestCase: BaseTestCase {
// MARK: - Properties
let searchPathDirectory: NSSearchPathDirectory = .CachesDirectory
let searchPathDomain: NSSearchPathDomainMask = .UserDomainMask
// MARK: - Tests
func testDownloadRequest() {
// Given
let numberOfLines = 100
let URLString = "http://httpbin.org/stream/\(numberOfLines)"
let destination = Alamofire.Request.suggestedDownloadDestination(directory: searchPathDirectory, domain: searchPathDomain)
let expectation = expectationWithDescription("Download request should download data to file: \(URLString)")
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var error: NSError?
// When
Alamofire.download(.GET, URLString, destination)
.response { responseRequest, responseResponse, _, responseError in
request = responseRequest
response = responseResponse
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertNil(error, "error should be nil")
let fileManager = NSFileManager.defaultManager()
let directory = fileManager.URLsForDirectory(self.searchPathDirectory, inDomains: self.searchPathDomain)[0] as! NSURL
var fileManagerError: NSError?
if let contents = fileManager.contentsOfDirectoryAtURL(directory, includingPropertiesForKeys: nil, options: .SkipsHiddenFiles, error: &fileManagerError) {
XCTAssertNil(fileManagerError, "fileManagerError should be nil")
#if os(iOS)
let suggestedFilename = "\(numberOfLines)"
#elseif os(OSX)
let suggestedFilename = "\(numberOfLines).json"
#endif
let predicate = NSPredicate(format: "lastPathComponent = '\(suggestedFilename)'")
let filteredContents = (contents as NSArray).filteredArrayUsingPredicate(predicate)
XCTAssertEqual(filteredContents.count, 1, "should have one file in Documents")
if let file = filteredContents.first as? NSURL {
XCTAssertEqual(file.lastPathComponent ?? "", "\(suggestedFilename)", "filename should be \(suggestedFilename)")
if let data = NSData(contentsOfURL: file) {
XCTAssertGreaterThan(data.length, 0, "data length should be non-zero")
} else {
XCTFail("data should exist for contents of URL")
}
fileManager.removeItemAtURL(file, error: nil)
} else {
XCTFail("file should not be nil")
}
} else {
XCTFail("contents should not be nil")
}
}
func testDownloadRequestWithProgress2() {
// Given
let randomBytes = 4 * 1024 * 1024
let URLString = "http://httpbin.org/bytes/\(randomBytes)"
let fileManager = NSFileManager.defaultManager()
let directory = fileManager.URLsForDirectory(self.searchPathDirectory, inDomains: self.searchPathDomain)[0] as! NSURL
let filename = "test_download_data"
let fileURL = directory.URLByAppendingPathComponent(filename)
let expectation = expectationWithDescription("Bytes download progress should be reported: \(URLString)")
var byteValues: [(bytes: Int64, totalBytes: Int64, totalBytesExpected: Int64)] = []
var progressValues: [(completedUnitCount: Int64, totalUnitCount: Int64)] = []
var responseRequest: NSURLRequest?
var responseResponse: NSHTTPURLResponse?
var responseData: AnyObject?
var responseError: NSError?
// When
let download = Alamofire.download(.GET, URLString) { _, _ in
return fileURL
}
download.progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
let bytes = (bytes: bytesRead, totalBytes: totalBytesRead, totalBytesExpected: totalBytesExpectedToRead)
byteValues.append(bytes)
let progress = (completedUnitCount: download.progress.completedUnitCount, totalUnitCount: download.progress.totalUnitCount)
progressValues.append(progress)
}
download.response { request, response, data, error in
responseRequest = request
responseResponse = response
responseData = data
responseError = error
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(responseRequest, "response request should not be nil")
XCTAssertNotNil(responseResponse, "response response should not be nil")
XCTAssertNil(responseData, "response data should be nil")
XCTAssertNil(responseError, "response error should be nil")
XCTAssertEqual(byteValues.count, progressValues.count, "byteValues count should equal progressValues count")
if byteValues.count == progressValues.count {
for index in 0..<byteValues.count {
let byteValue = byteValues[index]
let progressValue = progressValues[index]
XCTAssertGreaterThan(byteValue.bytes, 0, "reported bytes should always be greater than 0")
XCTAssertEqual(byteValue.totalBytes, progressValue.completedUnitCount, "total bytes should be equal to completed unit count")
XCTAssertEqual(byteValue.totalBytesExpected, progressValue.totalUnitCount, "total bytes expected should be equal to total unit count")
}
}
if let lastByteValue = byteValues.last,
lastProgressValue = progressValues.last
{
let byteValueFractionalCompletion = Double(lastByteValue.totalBytes) / Double(lastByteValue.totalBytesExpected)
let progressValueFractionalCompletion = Double(lastProgressValue.0) / Double(lastProgressValue.1)
XCTAssertEqual(byteValueFractionalCompletion, 1.0, "byte value fractional completion should equal 1.0")
XCTAssertEqual(progressValueFractionalCompletion, 1.0, "progress value fractional completion should equal 1.0")
} else {
XCTFail("last item in bytesValues and progressValues should not be nil")
}
var removalError: NSError?
fileManager.removeItemAtURL(fileURL, error: &removalError)
XCTAssertNil(removalError, "removal error should be nil")
}
}
| I'd actually like to hear everyone's testing philosophy here. I've always tried to follow the "test individual things" approach, and have a test for each specific thing you are testing (don't combine asserts for different things in the same test). I dont always end up with tests built that way, but I'm trying.
I've also been told tests are the only place its ok to repeat code over and over, and because you want to test specific things.
What are your thoughts?
| // DownloadTests.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Alamofire
import Foundation
import XCTest
class DownloadResponseTestCase: BaseTestCase {
// MARK: - Properties
let searchPathDirectory: NSSearchPathDirectory = .CachesDirectory
let searchPathDomain: NSSearchPathDomainMask = .UserDomainMask
// MARK: - Tests
func testDownloadRequest() {
// Given
let numberOfLines = 100
let URLString = "http://httpbin.org/stream/\(numberOfLines)"
let destination = Alamofire.Request.suggestedDownloadDestination(directory: searchPathDirectory, domain: searchPathDomain)
let expectation = expectationWithDescription("Download request should download data to file: \(URLString)")
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var error: NSError?
// When
Alamofire.download(.GET, URLString, destination)
.response { responseRequest, responseResponse, _, responseError in
request = responseRequest
response = responseResponse
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertNil(error, "error should be nil")
let fileManager = NSFileManager.defaultManager()
let directory = fileManager.URLsForDirectory(self.searchPathDirectory, inDomains: self.searchPathDomain)[0] as! NSURL
var fileManagerError: NSError?
if let contents = fileManager.contentsOfDirectoryAtURL(directory, includingPropertiesForKeys: nil, options: .SkipsHiddenFiles, error: &fileManagerError) {
XCTAssertNil(fileManagerError, "fileManagerError should be nil")
#if os(iOS)
let suggestedFilename = "\(numberOfLines)"
#elseif os(OSX)
let suggestedFilename = "\(numberOfLines).json"
#endif
let predicate = NSPredicate(format: "lastPathComponent = '\(suggestedFilename)'")
let filteredContents = (contents as NSArray).filteredArrayUsingPredicate(predicate)
XCTAssertEqual(filteredContents.count, 1, "should have one file in Documents")
if let file = filteredContents.first as? NSURL {
XCTAssertEqual(file.lastPathComponent ?? "", "\(suggestedFilename)", "filename should be \(suggestedFilename)")
if let data = NSData(contentsOfURL: file) {
XCTAssertGreaterThan(data.length, 0, "data length should be non-zero")
} else {
XCTFail("data should exist for contents of URL")
}
fileManager.removeItemAtURL(file, error: nil)
} else {
XCTFail("file should not be nil")
}
} else {
XCTFail("contents should not be nil")
}
}
func testDownloadRequestWithProgress() {
// Given
let randomBytes = 4 * 1024 * 1024
let URLString = "http://httpbin.org/bytes/\(randomBytes)"
let fileManager = NSFileManager.defaultManager()
let directory = fileManager.URLsForDirectory(self.searchPathDirectory, inDomains: self.searchPathDomain)[0] as! NSURL
let filename = "test_download_data"
let fileURL = directory.URLByAppendingPathComponent(filename)
let expectation = expectationWithDescription("Bytes download progress should be reported: \(URLString)")
var byteValues: [(bytes: Int64, totalBytes: Int64, totalBytesExpected: Int64)] = []
var progressValues: [(completedUnitCount: Int64, totalUnitCount: Int64)] = []
var responseRequest: NSURLRequest?
var responseResponse: NSHTTPURLResponse?
var responseData: AnyObject?
var responseError: NSError?
// When
let download = Alamofire.download(.GET, URLString) { _, _ in
return fileURL
}
download.progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
let bytes = (bytes: bytesRead, totalBytes: totalBytesRead, totalBytesExpected: totalBytesExpectedToRead)
byteValues.append(bytes)
let progress = (completedUnitCount: download.progress.completedUnitCount, totalUnitCount: download.progress.totalUnitCount)
progressValues.append(progress)
}
download.response { request, response, data, error in
responseRequest = request
responseResponse = response
responseData = data
responseError = error
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(responseRequest, "response request should not be nil")
XCTAssertNotNil(responseResponse, "response response should not be nil")
XCTAssertNil(responseData, "response data should be nil")
XCTAssertNil(responseError, "response error should be nil")
XCTAssertEqual(byteValues.count, progressValues.count, "byteValues count should equal progressValues count")
if byteValues.count == progressValues.count {
for index in 0..<byteValues.count {
let byteValue = byteValues[index]
let progressValue = progressValues[index]
XCTAssertGreaterThan(byteValue.bytes, 0, "reported bytes should always be greater than 0")
XCTAssertEqual(byteValue.totalBytes, progressValue.completedUnitCount, "total bytes should be equal to completed unit count")
XCTAssertEqual(byteValue.totalBytesExpected, progressValue.totalUnitCount, "total bytes expected should be equal to total unit count")
}
}
if let lastByteValue = byteValues.last,
lastProgressValue = progressValues.last
{
let byteValueFractionalCompletion = Double(lastByteValue.totalBytes) / Double(lastByteValue.totalBytesExpected)
let progressValueFractionalCompletion = Double(lastProgressValue.0) / Double(lastProgressValue.1)
XCTAssertEqual(byteValueFractionalCompletion, 1.0, "byte value fractional completion should equal 1.0")
XCTAssertEqual(progressValueFractionalCompletion, 1.0, "progress value fractional completion should equal 1.0")
} else {
XCTFail("last item in bytesValues and progressValues should not be nil")
}
var removalError: NSError?
fileManager.removeItemAtURL(fileURL, error: &removalError)
XCTAssertNil(removalError, "removal error should be nil")
}
}
| @@ -97,27 +97,41 @@ class DownloadResponseTestCase: BaseTestCase {
}
}
- func testDownloadRequestWithProgress() {
+ func testDownloadRequestWithProgress2() { | Tests/DownloadTests.swift | 0 | Swift | 0.5 | question | 466 | 177 | 177 | false | Created more robust data, upload and download progress tests | 494 | Alamofire/Alamofire | 41,690 | Swift | kcharwood | cnoon |
// DownloadTests.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Alamofire
import Foundation
import XCTest
class DownloadResponseTestCase: BaseTestCase {
// MARK: - Properties
let searchPathDirectory: NSSearchPathDirectory = .CachesDirectory
let searchPathDomain: NSSearchPathDomainMask = .UserDomainMask
// MARK: - Tests
func testDownloadRequest() {
// Given
let numberOfLines = 100
let URLString = "http://httpbin.org/stream/\(numberOfLines)"
let destination = Alamofire.Request.suggestedDownloadDestination(directory: searchPathDirectory, domain: searchPathDomain)
let expectation = expectationWithDescription("Download request should download data to file: \(URLString)")
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var error: NSError?
// When
Alamofire.download(.GET, URLString, destination)
.response { responseRequest, responseResponse, _, responseError in
request = responseRequest
response = responseResponse
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertNil(error, "error should be nil")
let fileManager = NSFileManager.defaultManager()
let directory = fileManager.URLsForDirectory(self.searchPathDirectory, inDomains: self.searchPathDomain)[0] as! NSURL
var fileManagerError: NSError?
if let contents = fileManager.contentsOfDirectoryAtURL(directory, includingPropertiesForKeys: nil, options: .SkipsHiddenFiles, error: &fileManagerError) {
XCTAssertNil(fileManagerError, "fileManagerError should be nil")
#if os(iOS)
let suggestedFilename = "\(numberOfLines)"
#elseif os(OSX)
let suggestedFilename = "\(numberOfLines).json"
#endif
let predicate = NSPredicate(format: "lastPathComponent = '\(suggestedFilename)'")
let filteredContents = (contents as NSArray).filteredArrayUsingPredicate(predicate)
XCTAssertEqual(filteredContents.count, 1, "should have one file in Documents")
if let file = filteredContents.first as? NSURL {
XCTAssertEqual(file.lastPathComponent ?? "", "\(suggestedFilename)", "filename should be \(suggestedFilename)")
if let data = NSData(contentsOfURL: file) {
XCTAssertGreaterThan(data.length, 0, "data length should be non-zero")
} else {
XCTFail("data should exist for contents of URL")
}
fileManager.removeItemAtURL(file, error: nil)
} else {
XCTFail("file should not be nil")
}
} else {
XCTFail("contents should not be nil")
}
}
func testDownloadRequestWithProgress2() {
// Given
let randomBytes = 4 * 1024 * 1024
let URLString = "http://httpbin.org/bytes/\(randomBytes)"
let fileManager = NSFileManager.defaultManager()
let directory = fileManager.URLsForDirectory(self.searchPathDirectory, inDomains: self.searchPathDomain)[0] as! NSURL
let filename = "test_download_data"
let fileURL = directory.URLByAppendingPathComponent(filename)
let expectation = expectationWithDescription("Bytes download progress should be reported: \(URLString)")
var byteValues: [(bytes: Int64, totalBytes: Int64, totalBytesExpected: Int64)] = []
var progressValues: [(completedUnitCount: Int64, totalUnitCount: Int64)] = []
var responseRequest: NSURLRequest?
var responseResponse: NSHTTPURLResponse?
var responseData: AnyObject?
var responseError: NSError?
// When
let download = Alamofire.download(.GET, URLString) { _, _ in
return fileURL
}
download.progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
let bytes = (bytes: bytesRead, totalBytes: totalBytesRead, totalBytesExpected: totalBytesExpectedToRead)
byteValues.append(bytes)
let progress = (completedUnitCount: download.progress.completedUnitCount, totalUnitCount: download.progress.totalUnitCount)
progressValues.append(progress)
}
download.response { request, response, data, error in
responseRequest = request
responseResponse = response
responseData = data
responseError = error
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(responseRequest, "response request should not be nil")
XCTAssertNotNil(responseResponse, "response response should not be nil")
XCTAssertNil(responseData, "response data should be nil")
XCTAssertNil(responseError, "response error should be nil")
XCTAssertEqual(byteValues.count, progressValues.count, "byteValues count should equal progressValues count")
if byteValues.count == progressValues.count {
for index in 0..<byteValues.count {
let byteValue = byteValues[index]
let progressValue = progressValues[index]
XCTAssertGreaterThan(byteValue.bytes, 0, "reported bytes should always be greater than 0")
XCTAssertEqual(byteValue.totalBytes, progressValue.completedUnitCount, "total bytes should be equal to completed unit count")
XCTAssertEqual(byteValue.totalBytesExpected, progressValue.totalUnitCount, "total bytes expected should be equal to total unit count")
}
}
if let lastByteValue = byteValues.last,
lastProgressValue = progressValues.last
{
let byteValueFractionalCompletion = Double(lastByteValue.totalBytes) / Double(lastByteValue.totalBytesExpected)
let progressValueFractionalCompletion = Double(lastProgressValue.0) / Double(lastProgressValue.1)
XCTAssertEqual(byteValueFractionalCompletion, 1.0, "byte value fractional completion should equal 1.0")
XCTAssertEqual(progressValueFractionalCompletion, 1.0, "progress value fractional completion should equal 1.0")
} else {
XCTFail("last item in bytesValues and progressValues should not be nil")
}
var removalError: NSError?
fileManager.removeItemAtURL(fileURL, error: &removalError)
XCTAssertNil(removalError, "removal error should be nil")
}
}
| @kcharwood My testing philosophy is to have tests setup situations that precisely emulate feature usage and assert as much as possible about the conditions that follow. Assertions themselves should be atomic (i.e. not testing compound conditions). Having the same assertions over and over across different tests is great—that's diligence. But if setup code is duplicated, there's a strong case to be made to consolidate those into a single test.
| // DownloadTests.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Alamofire
import Foundation
import XCTest
class DownloadResponseTestCase: BaseTestCase {
// MARK: - Properties
let searchPathDirectory: NSSearchPathDirectory = .CachesDirectory
let searchPathDomain: NSSearchPathDomainMask = .UserDomainMask
// MARK: - Tests
func testDownloadRequest() {
// Given
let numberOfLines = 100
let URLString = "http://httpbin.org/stream/\(numberOfLines)"
let destination = Alamofire.Request.suggestedDownloadDestination(directory: searchPathDirectory, domain: searchPathDomain)
let expectation = expectationWithDescription("Download request should download data to file: \(URLString)")
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var error: NSError?
// When
Alamofire.download(.GET, URLString, destination)
.response { responseRequest, responseResponse, _, responseError in
request = responseRequest
response = responseResponse
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertNil(error, "error should be nil")
let fileManager = NSFileManager.defaultManager()
let directory = fileManager.URLsForDirectory(self.searchPathDirectory, inDomains: self.searchPathDomain)[0] as! NSURL
var fileManagerError: NSError?
if let contents = fileManager.contentsOfDirectoryAtURL(directory, includingPropertiesForKeys: nil, options: .SkipsHiddenFiles, error: &fileManagerError) {
XCTAssertNil(fileManagerError, "fileManagerError should be nil")
#if os(iOS)
let suggestedFilename = "\(numberOfLines)"
#elseif os(OSX)
let suggestedFilename = "\(numberOfLines).json"
#endif
let predicate = NSPredicate(format: "lastPathComponent = '\(suggestedFilename)'")
let filteredContents = (contents as NSArray).filteredArrayUsingPredicate(predicate)
XCTAssertEqual(filteredContents.count, 1, "should have one file in Documents")
if let file = filteredContents.first as? NSURL {
XCTAssertEqual(file.lastPathComponent ?? "", "\(suggestedFilename)", "filename should be \(suggestedFilename)")
if let data = NSData(contentsOfURL: file) {
XCTAssertGreaterThan(data.length, 0, "data length should be non-zero")
} else {
XCTFail("data should exist for contents of URL")
}
fileManager.removeItemAtURL(file, error: nil)
} else {
XCTFail("file should not be nil")
}
} else {
XCTFail("contents should not be nil")
}
}
func testDownloadRequestWithProgress() {
// Given
let randomBytes = 4 * 1024 * 1024
let URLString = "http://httpbin.org/bytes/\(randomBytes)"
let fileManager = NSFileManager.defaultManager()
let directory = fileManager.URLsForDirectory(self.searchPathDirectory, inDomains: self.searchPathDomain)[0] as! NSURL
let filename = "test_download_data"
let fileURL = directory.URLByAppendingPathComponent(filename)
let expectation = expectationWithDescription("Bytes download progress should be reported: \(URLString)")
var byteValues: [(bytes: Int64, totalBytes: Int64, totalBytesExpected: Int64)] = []
var progressValues: [(completedUnitCount: Int64, totalUnitCount: Int64)] = []
var responseRequest: NSURLRequest?
var responseResponse: NSHTTPURLResponse?
var responseData: AnyObject?
var responseError: NSError?
// When
let download = Alamofire.download(.GET, URLString) { _, _ in
return fileURL
}
download.progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
let bytes = (bytes: bytesRead, totalBytes: totalBytesRead, totalBytesExpected: totalBytesExpectedToRead)
byteValues.append(bytes)
let progress = (completedUnitCount: download.progress.completedUnitCount, totalUnitCount: download.progress.totalUnitCount)
progressValues.append(progress)
}
download.response { request, response, data, error in
responseRequest = request
responseResponse = response
responseData = data
responseError = error
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(responseRequest, "response request should not be nil")
XCTAssertNotNil(responseResponse, "response response should not be nil")
XCTAssertNil(responseData, "response data should be nil")
XCTAssertNil(responseError, "response error should be nil")
XCTAssertEqual(byteValues.count, progressValues.count, "byteValues count should equal progressValues count")
if byteValues.count == progressValues.count {
for index in 0..<byteValues.count {
let byteValue = byteValues[index]
let progressValue = progressValues[index]
XCTAssertGreaterThan(byteValue.bytes, 0, "reported bytes should always be greater than 0")
XCTAssertEqual(byteValue.totalBytes, progressValue.completedUnitCount, "total bytes should be equal to completed unit count")
XCTAssertEqual(byteValue.totalBytesExpected, progressValue.totalUnitCount, "total bytes expected should be equal to total unit count")
}
}
if let lastByteValue = byteValues.last,
lastProgressValue = progressValues.last
{
let byteValueFractionalCompletion = Double(lastByteValue.totalBytes) / Double(lastByteValue.totalBytesExpected)
let progressValueFractionalCompletion = Double(lastProgressValue.0) / Double(lastProgressValue.1)
XCTAssertEqual(byteValueFractionalCompletion, 1.0, "byte value fractional completion should equal 1.0")
XCTAssertEqual(progressValueFractionalCompletion, 1.0, "progress value fractional completion should equal 1.0")
} else {
XCTFail("last item in bytesValues and progressValues should not be nil")
}
var removalError: NSError?
fileManager.removeItemAtURL(fileURL, error: &removalError)
XCTAssertNil(removalError, "removal error should be nil")
}
}
| @@ -97,27 +97,41 @@ class DownloadResponseTestCase: BaseTestCase {
}
}
- func testDownloadRequestWithProgress() {
+ func testDownloadRequestWithProgress2() { | Tests/DownloadTests.swift | 0 | Swift | 0.5 | refactor | 446 | 177 | 177 | false | Created more robust data, upload and download progress tests | 494 | Alamofire/Alamofire | 41,690 | Swift | mattt | cnoon |
// DownloadTests.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Alamofire
import Foundation
import XCTest
class DownloadResponseTestCase: BaseTestCase {
// MARK: - Properties
let searchPathDirectory: NSSearchPathDirectory = .CachesDirectory
let searchPathDomain: NSSearchPathDomainMask = .UserDomainMask
// MARK: - Tests
func testDownloadRequest() {
// Given
let numberOfLines = 100
let URLString = "http://httpbin.org/stream/\(numberOfLines)"
let destination = Alamofire.Request.suggestedDownloadDestination(directory: searchPathDirectory, domain: searchPathDomain)
let expectation = expectationWithDescription("Download request should download data to file: \(URLString)")
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var error: NSError?
// When
Alamofire.download(.GET, URLString, destination)
.response { responseRequest, responseResponse, _, responseError in
request = responseRequest
response = responseResponse
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertNil(error, "error should be nil")
let fileManager = NSFileManager.defaultManager()
let directory = fileManager.URLsForDirectory(self.searchPathDirectory, inDomains: self.searchPathDomain)[0] as! NSURL
var fileManagerError: NSError?
if let contents = fileManager.contentsOfDirectoryAtURL(directory, includingPropertiesForKeys: nil, options: .SkipsHiddenFiles, error: &fileManagerError) {
XCTAssertNil(fileManagerError, "fileManagerError should be nil")
#if os(iOS)
let suggestedFilename = "\(numberOfLines)"
#elseif os(OSX)
let suggestedFilename = "\(numberOfLines).json"
#endif
let predicate = NSPredicate(format: "lastPathComponent = '\(suggestedFilename)'")
let filteredContents = (contents as NSArray).filteredArrayUsingPredicate(predicate)
XCTAssertEqual(filteredContents.count, 1, "should have one file in Documents")
if let file = filteredContents.first as? NSURL {
XCTAssertEqual(file.lastPathComponent ?? "", "\(suggestedFilename)", "filename should be \(suggestedFilename)")
if let data = NSData(contentsOfURL: file) {
XCTAssertGreaterThan(data.length, 0, "data length should be non-zero")
} else {
XCTFail("data should exist for contents of URL")
}
fileManager.removeItemAtURL(file, error: nil)
} else {
XCTFail("file should not be nil")
}
} else {
XCTFail("contents should not be nil")
}
}
func testDownloadRequestWithProgress2() {
// Given
let randomBytes = 4 * 1024 * 1024
let URLString = "http://httpbin.org/bytes/\(randomBytes)"
let fileManager = NSFileManager.defaultManager()
let directory = fileManager.URLsForDirectory(self.searchPathDirectory, inDomains: self.searchPathDomain)[0] as! NSURL
let filename = "test_download_data"
let fileURL = directory.URLByAppendingPathComponent(filename)
let expectation = expectationWithDescription("Bytes download progress should be reported: \(URLString)")
var byteValues: [(bytes: Int64, totalBytes: Int64, totalBytesExpected: Int64)] = []
var progressValues: [(completedUnitCount: Int64, totalUnitCount: Int64)] = []
var responseRequest: NSURLRequest?
var responseResponse: NSHTTPURLResponse?
var responseData: AnyObject?
var responseError: NSError?
// When
let download = Alamofire.download(.GET, URLString) { _, _ in
return fileURL
}
download.progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
let bytes = (bytes: bytesRead, totalBytes: totalBytesRead, totalBytesExpected: totalBytesExpectedToRead)
byteValues.append(bytes)
let progress = (completedUnitCount: download.progress.completedUnitCount, totalUnitCount: download.progress.totalUnitCount)
progressValues.append(progress)
}
download.response { request, response, data, error in
responseRequest = request
responseResponse = response
responseData = data
responseError = error
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(responseRequest, "response request should not be nil")
XCTAssertNotNil(responseResponse, "response response should not be nil")
XCTAssertNil(responseData, "response data should be nil")
XCTAssertNil(responseError, "response error should be nil")
XCTAssertEqual(byteValues.count, progressValues.count, "byteValues count should equal progressValues count")
if byteValues.count == progressValues.count {
for index in 0..<byteValues.count {
let byteValue = byteValues[index]
let progressValue = progressValues[index]
XCTAssertGreaterThan(byteValue.bytes, 0, "reported bytes should always be greater than 0")
XCTAssertEqual(byteValue.totalBytes, progressValue.completedUnitCount, "total bytes should be equal to completed unit count")
XCTAssertEqual(byteValue.totalBytesExpected, progressValue.totalUnitCount, "total bytes expected should be equal to total unit count")
}
}
if let lastByteValue = byteValues.last,
lastProgressValue = progressValues.last
{
let byteValueFractionalCompletion = Double(lastByteValue.totalBytes) / Double(lastByteValue.totalBytesExpected)
let progressValueFractionalCompletion = Double(lastProgressValue.0) / Double(lastProgressValue.1)
XCTAssertEqual(byteValueFractionalCompletion, 1.0, "byte value fractional completion should equal 1.0")
XCTAssertEqual(progressValueFractionalCompletion, 1.0, "progress value fractional completion should equal 1.0")
} else {
XCTFail("last item in bytesValues and progressValues should not be nil")
}
var removalError: NSError?
fileManager.removeItemAtURL(fileURL, error: &removalError)
XCTAssertNil(removalError, "removal error should be nil")
}
}
| But as far as test names go, they should be descriptive. If there's a name conflict—again, that's a smell of duplication and a candidate for consolidation.
| // DownloadTests.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Alamofire
import Foundation
import XCTest
class DownloadResponseTestCase: BaseTestCase {
// MARK: - Properties
let searchPathDirectory: NSSearchPathDirectory = .CachesDirectory
let searchPathDomain: NSSearchPathDomainMask = .UserDomainMask
// MARK: - Tests
func testDownloadRequest() {
// Given
let numberOfLines = 100
let URLString = "http://httpbin.org/stream/\(numberOfLines)"
let destination = Alamofire.Request.suggestedDownloadDestination(directory: searchPathDirectory, domain: searchPathDomain)
let expectation = expectationWithDescription("Download request should download data to file: \(URLString)")
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var error: NSError?
// When
Alamofire.download(.GET, URLString, destination)
.response { responseRequest, responseResponse, _, responseError in
request = responseRequest
response = responseResponse
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertNil(error, "error should be nil")
let fileManager = NSFileManager.defaultManager()
let directory = fileManager.URLsForDirectory(self.searchPathDirectory, inDomains: self.searchPathDomain)[0] as! NSURL
var fileManagerError: NSError?
if let contents = fileManager.contentsOfDirectoryAtURL(directory, includingPropertiesForKeys: nil, options: .SkipsHiddenFiles, error: &fileManagerError) {
XCTAssertNil(fileManagerError, "fileManagerError should be nil")
#if os(iOS)
let suggestedFilename = "\(numberOfLines)"
#elseif os(OSX)
let suggestedFilename = "\(numberOfLines).json"
#endif
let predicate = NSPredicate(format: "lastPathComponent = '\(suggestedFilename)'")
let filteredContents = (contents as NSArray).filteredArrayUsingPredicate(predicate)
XCTAssertEqual(filteredContents.count, 1, "should have one file in Documents")
if let file = filteredContents.first as? NSURL {
XCTAssertEqual(file.lastPathComponent ?? "", "\(suggestedFilename)", "filename should be \(suggestedFilename)")
if let data = NSData(contentsOfURL: file) {
XCTAssertGreaterThan(data.length, 0, "data length should be non-zero")
} else {
XCTFail("data should exist for contents of URL")
}
fileManager.removeItemAtURL(file, error: nil)
} else {
XCTFail("file should not be nil")
}
} else {
XCTFail("contents should not be nil")
}
}
func testDownloadRequestWithProgress() {
// Given
let randomBytes = 4 * 1024 * 1024
let URLString = "http://httpbin.org/bytes/\(randomBytes)"
let fileManager = NSFileManager.defaultManager()
let directory = fileManager.URLsForDirectory(self.searchPathDirectory, inDomains: self.searchPathDomain)[0] as! NSURL
let filename = "test_download_data"
let fileURL = directory.URLByAppendingPathComponent(filename)
let expectation = expectationWithDescription("Bytes download progress should be reported: \(URLString)")
var byteValues: [(bytes: Int64, totalBytes: Int64, totalBytesExpected: Int64)] = []
var progressValues: [(completedUnitCount: Int64, totalUnitCount: Int64)] = []
var responseRequest: NSURLRequest?
var responseResponse: NSHTTPURLResponse?
var responseData: AnyObject?
var responseError: NSError?
// When
let download = Alamofire.download(.GET, URLString) { _, _ in
return fileURL
}
download.progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
let bytes = (bytes: bytesRead, totalBytes: totalBytesRead, totalBytesExpected: totalBytesExpectedToRead)
byteValues.append(bytes)
let progress = (completedUnitCount: download.progress.completedUnitCount, totalUnitCount: download.progress.totalUnitCount)
progressValues.append(progress)
}
download.response { request, response, data, error in
responseRequest = request
responseResponse = response
responseData = data
responseError = error
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(responseRequest, "response request should not be nil")
XCTAssertNotNil(responseResponse, "response response should not be nil")
XCTAssertNil(responseData, "response data should be nil")
XCTAssertNil(responseError, "response error should be nil")
XCTAssertEqual(byteValues.count, progressValues.count, "byteValues count should equal progressValues count")
if byteValues.count == progressValues.count {
for index in 0..<byteValues.count {
let byteValue = byteValues[index]
let progressValue = progressValues[index]
XCTAssertGreaterThan(byteValue.bytes, 0, "reported bytes should always be greater than 0")
XCTAssertEqual(byteValue.totalBytes, progressValue.completedUnitCount, "total bytes should be equal to completed unit count")
XCTAssertEqual(byteValue.totalBytesExpected, progressValue.totalUnitCount, "total bytes expected should be equal to total unit count")
}
}
if let lastByteValue = byteValues.last,
lastProgressValue = progressValues.last
{
let byteValueFractionalCompletion = Double(lastByteValue.totalBytes) / Double(lastByteValue.totalBytesExpected)
let progressValueFractionalCompletion = Double(lastProgressValue.0) / Double(lastProgressValue.1)
XCTAssertEqual(byteValueFractionalCompletion, 1.0, "byte value fractional completion should equal 1.0")
XCTAssertEqual(progressValueFractionalCompletion, 1.0, "progress value fractional completion should equal 1.0")
} else {
XCTFail("last item in bytesValues and progressValues should not be nil")
}
var removalError: NSError?
fileManager.removeItemAtURL(fileURL, error: &removalError)
XCTAssertNil(removalError, "removal error should be nil")
}
}
| @@ -97,27 +97,41 @@ class DownloadResponseTestCase: BaseTestCase {
}
}
- func testDownloadRequestWithProgress() {
+ func testDownloadRequestWithProgress2() { | Tests/DownloadTests.swift | 0 | Swift | 0.429 | suggestion | 156 | 177 | 177 | false | Created more robust data, upload and download progress tests | 494 | Alamofire/Alamofire | 41,690 | Swift | mattt | cnoon |
// DownloadTests.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Alamofire
import Foundation
import XCTest
class DownloadResponseTestCase: BaseTestCase {
// MARK: - Properties
let searchPathDirectory: NSSearchPathDirectory = .CachesDirectory
let searchPathDomain: NSSearchPathDomainMask = .UserDomainMask
// MARK: - Tests
func testDownloadRequest() {
// Given
let numberOfLines = 100
let URLString = "http://httpbin.org/stream/\(numberOfLines)"
let destination = Alamofire.Request.suggestedDownloadDestination(directory: searchPathDirectory, domain: searchPathDomain)
let expectation = expectationWithDescription("Download request should download data to file: \(URLString)")
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var error: NSError?
// When
Alamofire.download(.GET, URLString, destination)
.response { responseRequest, responseResponse, _, responseError in
request = responseRequest
response = responseResponse
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertNil(error, "error should be nil")
let fileManager = NSFileManager.defaultManager()
let directory = fileManager.URLsForDirectory(self.searchPathDirectory, inDomains: self.searchPathDomain)[0] as! NSURL
var fileManagerError: NSError?
if let contents = fileManager.contentsOfDirectoryAtURL(directory, includingPropertiesForKeys: nil, options: .SkipsHiddenFiles, error: &fileManagerError) {
XCTAssertNil(fileManagerError, "fileManagerError should be nil")
#if os(iOS)
let suggestedFilename = "\(numberOfLines)"
#elseif os(OSX)
let suggestedFilename = "\(numberOfLines).json"
#endif
let predicate = NSPredicate(format: "lastPathComponent = '\(suggestedFilename)'")
let filteredContents = (contents as NSArray).filteredArrayUsingPredicate(predicate)
XCTAssertEqual(filteredContents.count, 1, "should have one file in Documents")
if let file = filteredContents.first as? NSURL {
XCTAssertEqual(file.lastPathComponent ?? "", "\(suggestedFilename)", "filename should be \(suggestedFilename)")
if let data = NSData(contentsOfURL: file) {
XCTAssertGreaterThan(data.length, 0, "data length should be non-zero")
} else {
XCTFail("data should exist for contents of URL")
}
fileManager.removeItemAtURL(file, error: nil)
} else {
XCTFail("file should not be nil")
}
} else {
XCTFail("contents should not be nil")
}
}
func testDownloadRequestWithProgress2() {
// Given
let randomBytes = 4 * 1024 * 1024
let URLString = "http://httpbin.org/bytes/\(randomBytes)"
let fileManager = NSFileManager.defaultManager()
let directory = fileManager.URLsForDirectory(self.searchPathDirectory, inDomains: self.searchPathDomain)[0] as! NSURL
let filename = "test_download_data"
let fileURL = directory.URLByAppendingPathComponent(filename)
let expectation = expectationWithDescription("Bytes download progress should be reported: \(URLString)")
var byteValues: [(bytes: Int64, totalBytes: Int64, totalBytesExpected: Int64)] = []
var progressValues: [(completedUnitCount: Int64, totalUnitCount: Int64)] = []
var responseRequest: NSURLRequest?
var responseResponse: NSHTTPURLResponse?
var responseData: AnyObject?
var responseError: NSError?
// When
let download = Alamofire.download(.GET, URLString) { _, _ in
return fileURL
}
download.progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
let bytes = (bytes: bytesRead, totalBytes: totalBytesRead, totalBytesExpected: totalBytesExpectedToRead)
byteValues.append(bytes)
let progress = (completedUnitCount: download.progress.completedUnitCount, totalUnitCount: download.progress.totalUnitCount)
progressValues.append(progress)
}
download.response { request, response, data, error in
responseRequest = request
responseResponse = response
responseData = data
responseError = error
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(responseRequest, "response request should not be nil")
XCTAssertNotNil(responseResponse, "response response should not be nil")
XCTAssertNil(responseData, "response data should be nil")
XCTAssertNil(responseError, "response error should be nil")
XCTAssertEqual(byteValues.count, progressValues.count, "byteValues count should equal progressValues count")
if byteValues.count == progressValues.count {
for index in 0..<byteValues.count {
let byteValue = byteValues[index]
let progressValue = progressValues[index]
XCTAssertGreaterThan(byteValue.bytes, 0, "reported bytes should always be greater than 0")
XCTAssertEqual(byteValue.totalBytes, progressValue.completedUnitCount, "total bytes should be equal to completed unit count")
XCTAssertEqual(byteValue.totalBytesExpected, progressValue.totalUnitCount, "total bytes expected should be equal to total unit count")
}
}
if let lastByteValue = byteValues.last,
lastProgressValue = progressValues.last
{
let byteValueFractionalCompletion = Double(lastByteValue.totalBytes) / Double(lastByteValue.totalBytesExpected)
let progressValueFractionalCompletion = Double(lastProgressValue.0) / Double(lastProgressValue.1)
XCTAssertEqual(byteValueFractionalCompletion, 1.0, "byte value fractional completion should equal 1.0")
XCTAssertEqual(progressValueFractionalCompletion, 1.0, "progress value fractional completion should equal 1.0")
} else {
XCTFail("last item in bytesValues and progressValues should not be nil")
}
var removalError: NSError?
fileManager.removeItemAtURL(fileURL, error: &removalError)
XCTAssertNil(removalError, "removal error should be nil")
}
}
| #### Name Change
I'm on it...good catch!
#### Repeating Yourself in Tests
I agree. I don't think there's any issue with repeating yourself in tests. I think it's advantageous to use a small amount of inheritance for simple things, but otherwise just repeat the logic so the majority of the code resides directly in the test or at least in the same test file. The more test logic that resides directly in the test method, the easier it is to quickly see all the moving parts of the test.
#### Test Individual Things
Great question @kcharwood. I'm going to try to break down my testing approach here and would love everyone's feedback.
I feel that the philosophy of "Test Individual Things" is a bit outdated when applied to one test, one assert. XCTest can continue running your test even if you trip an assertion. It's perfectly fine to have multiple assertions within the same test, it will report them all to you. As long as you have a policy of always keeping your test suite green, why does it matter that you have one test that actually has multiple failures? If your test suite cannot continue if it fails on an assertion, then I completely agree with the philosophy.
With that said, I do believe there's merit in attempting to write more focused tests. IMO, tests should focus on a particular operation and break it down into as small of unit as possible, then test the results. Next, you create a new set of input parameters, run the operation again, test the results. Rinse and repeat. Testing individual things to me means "test individual operations", not being limited to only have a single assertion in your test.
I also think this philosophy tends to break down with integration tests. Let's take the download tests for example. I just counted 23 different asserts in those two methods, some of which are called upwards of 20 times in a for loop. If we broke this out into individual tests, we'd be looking at thousands of lines of code to test the same logic. When you end up having to repeat yourself that many times, you make copy/paste errors and I think it makes your tests more fragile. I also believe it makes it difficult to understand what is really being tested since almost every test looks the same. Good descriptive names certainly help, but it gets super repetitive to anyone that didn't actually write the tests in the first place.
I could certainly be convinced in those download tests that we should have individual tests more like the following:
1. Successful download request (test completion handler arguments)
2. Failed download request due to bad URL (test completion handler arguments)
3. Failed download request due to bad file path (test completion handler arguments)
4. Successful download request testing only the progress values
5. Failed download request testing only the progress values
It's difficult for me to see how splitting each of these tests up into 4 or 5 additional methods to test each of these parameters would be a "better" overall approach to appease the testing gods. Especially in the case of the progress tests. Additionally, we wouldn't just be able to move the common logic into a "setup" type method, because the majority of the setup parameters get passed into the actual function being tested. While we could pass back a tuple back with upwards of 5 or 6 parameters inside it, I think our tuples would be getting a bit out of control.
One final point that seems a bit strange to me is how we can actually confirm that our single assertion test really did pass successfully if we don't test all the results that we expected? For example, if I make a data request, I expect that the payload data will exist, and I won't receive an error. If I split these into two different tests, how do I know that it is truly working? What if I'm for some reason I am actually receiving both data and an error, and the way I wrote my tests makes it unlikely that I would be able to catch that condition? That may not be the best example, but hopefully the idea of that issue came across. Dynamic operations, such as networking, could benefit from testing all resulting values in the operation rather than a lone expected one to always cover the "unexpected" behaviors.
In summary, I'm all for writing the best tests possible. I'd love everyone's feedback and would love to find a testing strategy that everyone agrees on and is happy with. My two cents...
| // DownloadTests.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Alamofire
import Foundation
import XCTest
class DownloadResponseTestCase: BaseTestCase {
// MARK: - Properties
let searchPathDirectory: NSSearchPathDirectory = .CachesDirectory
let searchPathDomain: NSSearchPathDomainMask = .UserDomainMask
// MARK: - Tests
func testDownloadRequest() {
// Given
let numberOfLines = 100
let URLString = "http://httpbin.org/stream/\(numberOfLines)"
let destination = Alamofire.Request.suggestedDownloadDestination(directory: searchPathDirectory, domain: searchPathDomain)
let expectation = expectationWithDescription("Download request should download data to file: \(URLString)")
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var error: NSError?
// When
Alamofire.download(.GET, URLString, destination)
.response { responseRequest, responseResponse, _, responseError in
request = responseRequest
response = responseResponse
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertNil(error, "error should be nil")
let fileManager = NSFileManager.defaultManager()
let directory = fileManager.URLsForDirectory(self.searchPathDirectory, inDomains: self.searchPathDomain)[0] as! NSURL
var fileManagerError: NSError?
if let contents = fileManager.contentsOfDirectoryAtURL(directory, includingPropertiesForKeys: nil, options: .SkipsHiddenFiles, error: &fileManagerError) {
XCTAssertNil(fileManagerError, "fileManagerError should be nil")
#if os(iOS)
let suggestedFilename = "\(numberOfLines)"
#elseif os(OSX)
let suggestedFilename = "\(numberOfLines).json"
#endif
let predicate = NSPredicate(format: "lastPathComponent = '\(suggestedFilename)'")
let filteredContents = (contents as NSArray).filteredArrayUsingPredicate(predicate)
XCTAssertEqual(filteredContents.count, 1, "should have one file in Documents")
if let file = filteredContents.first as? NSURL {
XCTAssertEqual(file.lastPathComponent ?? "", "\(suggestedFilename)", "filename should be \(suggestedFilename)")
if let data = NSData(contentsOfURL: file) {
XCTAssertGreaterThan(data.length, 0, "data length should be non-zero")
} else {
XCTFail("data should exist for contents of URL")
}
fileManager.removeItemAtURL(file, error: nil)
} else {
XCTFail("file should not be nil")
}
} else {
XCTFail("contents should not be nil")
}
}
func testDownloadRequestWithProgress() {
// Given
let randomBytes = 4 * 1024 * 1024
let URLString = "http://httpbin.org/bytes/\(randomBytes)"
let fileManager = NSFileManager.defaultManager()
let directory = fileManager.URLsForDirectory(self.searchPathDirectory, inDomains: self.searchPathDomain)[0] as! NSURL
let filename = "test_download_data"
let fileURL = directory.URLByAppendingPathComponent(filename)
let expectation = expectationWithDescription("Bytes download progress should be reported: \(URLString)")
var byteValues: [(bytes: Int64, totalBytes: Int64, totalBytesExpected: Int64)] = []
var progressValues: [(completedUnitCount: Int64, totalUnitCount: Int64)] = []
var responseRequest: NSURLRequest?
var responseResponse: NSHTTPURLResponse?
var responseData: AnyObject?
var responseError: NSError?
// When
let download = Alamofire.download(.GET, URLString) { _, _ in
return fileURL
}
download.progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
let bytes = (bytes: bytesRead, totalBytes: totalBytesRead, totalBytesExpected: totalBytesExpectedToRead)
byteValues.append(bytes)
let progress = (completedUnitCount: download.progress.completedUnitCount, totalUnitCount: download.progress.totalUnitCount)
progressValues.append(progress)
}
download.response { request, response, data, error in
responseRequest = request
responseResponse = response
responseData = data
responseError = error
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(responseRequest, "response request should not be nil")
XCTAssertNotNil(responseResponse, "response response should not be nil")
XCTAssertNil(responseData, "response data should be nil")
XCTAssertNil(responseError, "response error should be nil")
XCTAssertEqual(byteValues.count, progressValues.count, "byteValues count should equal progressValues count")
if byteValues.count == progressValues.count {
for index in 0..<byteValues.count {
let byteValue = byteValues[index]
let progressValue = progressValues[index]
XCTAssertGreaterThan(byteValue.bytes, 0, "reported bytes should always be greater than 0")
XCTAssertEqual(byteValue.totalBytes, progressValue.completedUnitCount, "total bytes should be equal to completed unit count")
XCTAssertEqual(byteValue.totalBytesExpected, progressValue.totalUnitCount, "total bytes expected should be equal to total unit count")
}
}
if let lastByteValue = byteValues.last,
lastProgressValue = progressValues.last
{
let byteValueFractionalCompletion = Double(lastByteValue.totalBytes) / Double(lastByteValue.totalBytesExpected)
let progressValueFractionalCompletion = Double(lastProgressValue.0) / Double(lastProgressValue.1)
XCTAssertEqual(byteValueFractionalCompletion, 1.0, "byte value fractional completion should equal 1.0")
XCTAssertEqual(progressValueFractionalCompletion, 1.0, "progress value fractional completion should equal 1.0")
} else {
XCTFail("last item in bytesValues and progressValues should not be nil")
}
var removalError: NSError?
fileManager.removeItemAtURL(fileURL, error: &removalError)
XCTAssertNil(removalError, "removal error should be nil")
}
}
| @@ -97,27 +97,41 @@ class DownloadResponseTestCase: BaseTestCase {
}
}
- func testDownloadRequestWithProgress() {
+ func testDownloadRequestWithProgress2() { | Tests/DownloadTests.swift | 0 | Swift | 0.643 | bug | 4,419 | 177 | 177 | false | Created more robust data, upload and download progress tests | 494 | Alamofire/Alamofire | 41,690 | Swift | cnoon | cnoon |
// DownloadTests.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Alamofire
import Foundation
import XCTest
class DownloadResponseTestCase: BaseTestCase {
// MARK: - Properties
let searchPathDirectory: NSSearchPathDirectory = .CachesDirectory
let searchPathDomain: NSSearchPathDomainMask = .UserDomainMask
// MARK: - Tests
func testDownloadRequest() {
// Given
let numberOfLines = 100
let URLString = "http://httpbin.org/stream/\(numberOfLines)"
let destination = Alamofire.Request.suggestedDownloadDestination(directory: searchPathDirectory, domain: searchPathDomain)
let expectation = expectationWithDescription("Download request should download data to file: \(URLString)")
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var error: NSError?
// When
Alamofire.download(.GET, URLString, destination)
.response { responseRequest, responseResponse, _, responseError in
request = responseRequest
response = responseResponse
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertNil(error, "error should be nil")
let fileManager = NSFileManager.defaultManager()
let directory = fileManager.URLsForDirectory(self.searchPathDirectory, inDomains: self.searchPathDomain)[0] as! NSURL
var fileManagerError: NSError?
if let contents = fileManager.contentsOfDirectoryAtURL(directory, includingPropertiesForKeys: nil, options: .SkipsHiddenFiles, error: &fileManagerError) {
XCTAssertNil(fileManagerError, "fileManagerError should be nil")
#if os(iOS)
let suggestedFilename = "\(numberOfLines)"
#elseif os(OSX)
let suggestedFilename = "\(numberOfLines).json"
#endif
let predicate = NSPredicate(format: "lastPathComponent = '\(suggestedFilename)'")
let filteredContents = (contents as NSArray).filteredArrayUsingPredicate(predicate)
XCTAssertEqual(filteredContents.count, 1, "should have one file in Documents")
if let file = filteredContents.first as? NSURL {
XCTAssertEqual(file.lastPathComponent ?? "", "\(suggestedFilename)", "filename should be \(suggestedFilename)")
if let data = NSData(contentsOfURL: file) {
XCTAssertGreaterThan(data.length, 0, "data length should be non-zero")
} else {
XCTFail("data should exist for contents of URL")
}
fileManager.removeItemAtURL(file, error: nil)
} else {
XCTFail("file should not be nil")
}
} else {
XCTFail("contents should not be nil")
}
}
func testDownloadRequestWithProgress2() {
// Given
let randomBytes = 4 * 1024 * 1024
let URLString = "http://httpbin.org/bytes/\(randomBytes)"
let fileManager = NSFileManager.defaultManager()
let directory = fileManager.URLsForDirectory(self.searchPathDirectory, inDomains: self.searchPathDomain)[0] as! NSURL
let filename = "test_download_data"
let fileURL = directory.URLByAppendingPathComponent(filename)
let expectation = expectationWithDescription("Bytes download progress should be reported: \(URLString)")
var byteValues: [(bytes: Int64, totalBytes: Int64, totalBytesExpected: Int64)] = []
var progressValues: [(completedUnitCount: Int64, totalUnitCount: Int64)] = []
var responseRequest: NSURLRequest?
var responseResponse: NSHTTPURLResponse?
var responseData: AnyObject?
var responseError: NSError?
// When
let download = Alamofire.download(.GET, URLString) { _, _ in
return fileURL
}
download.progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
let bytes = (bytes: bytesRead, totalBytes: totalBytesRead, totalBytesExpected: totalBytesExpectedToRead)
byteValues.append(bytes)
let progress = (completedUnitCount: download.progress.completedUnitCount, totalUnitCount: download.progress.totalUnitCount)
progressValues.append(progress)
}
download.response { request, response, data, error in
responseRequest = request
responseResponse = response
responseData = data
responseError = error
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(responseRequest, "response request should not be nil")
XCTAssertNotNil(responseResponse, "response response should not be nil")
XCTAssertNil(responseData, "response data should be nil")
XCTAssertNil(responseError, "response error should be nil")
XCTAssertEqual(byteValues.count, progressValues.count, "byteValues count should equal progressValues count")
if byteValues.count == progressValues.count {
for index in 0..<byteValues.count {
let byteValue = byteValues[index]
let progressValue = progressValues[index]
XCTAssertGreaterThan(byteValue.bytes, 0, "reported bytes should always be greater than 0")
XCTAssertEqual(byteValue.totalBytes, progressValue.completedUnitCount, "total bytes should be equal to completed unit count")
XCTAssertEqual(byteValue.totalBytesExpected, progressValue.totalUnitCount, "total bytes expected should be equal to total unit count")
}
}
if let lastByteValue = byteValues.last,
lastProgressValue = progressValues.last
{
let byteValueFractionalCompletion = Double(lastByteValue.totalBytes) / Double(lastByteValue.totalBytesExpected)
let progressValueFractionalCompletion = Double(lastProgressValue.0) / Double(lastProgressValue.1)
XCTAssertEqual(byteValueFractionalCompletion, 1.0, "byte value fractional completion should equal 1.0")
XCTAssertEqual(progressValueFractionalCompletion, 1.0, "progress value fractional completion should equal 1.0")
} else {
XCTFail("last item in bytesValues and progressValues should not be nil")
}
var removalError: NSError?
fileManager.removeItemAtURL(fileURL, error: &removalError)
XCTAssertNil(removalError, "removal error should be nil")
}
}
| Method name has been fixed and force pushed.
| // DownloadTests.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Alamofire
import Foundation
import XCTest
class DownloadResponseTestCase: BaseTestCase {
// MARK: - Properties
let searchPathDirectory: NSSearchPathDirectory = .CachesDirectory
let searchPathDomain: NSSearchPathDomainMask = .UserDomainMask
// MARK: - Tests
func testDownloadRequest() {
// Given
let numberOfLines = 100
let URLString = "http://httpbin.org/stream/\(numberOfLines)"
let destination = Alamofire.Request.suggestedDownloadDestination(directory: searchPathDirectory, domain: searchPathDomain)
let expectation = expectationWithDescription("Download request should download data to file: \(URLString)")
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var error: NSError?
// When
Alamofire.download(.GET, URLString, destination)
.response { responseRequest, responseResponse, _, responseError in
request = responseRequest
response = responseResponse
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertNil(error, "error should be nil")
let fileManager = NSFileManager.defaultManager()
let directory = fileManager.URLsForDirectory(self.searchPathDirectory, inDomains: self.searchPathDomain)[0] as! NSURL
var fileManagerError: NSError?
if let contents = fileManager.contentsOfDirectoryAtURL(directory, includingPropertiesForKeys: nil, options: .SkipsHiddenFiles, error: &fileManagerError) {
XCTAssertNil(fileManagerError, "fileManagerError should be nil")
#if os(iOS)
let suggestedFilename = "\(numberOfLines)"
#elseif os(OSX)
let suggestedFilename = "\(numberOfLines).json"
#endif
let predicate = NSPredicate(format: "lastPathComponent = '\(suggestedFilename)'")
let filteredContents = (contents as NSArray).filteredArrayUsingPredicate(predicate)
XCTAssertEqual(filteredContents.count, 1, "should have one file in Documents")
if let file = filteredContents.first as? NSURL {
XCTAssertEqual(file.lastPathComponent ?? "", "\(suggestedFilename)", "filename should be \(suggestedFilename)")
if let data = NSData(contentsOfURL: file) {
XCTAssertGreaterThan(data.length, 0, "data length should be non-zero")
} else {
XCTFail("data should exist for contents of URL")
}
fileManager.removeItemAtURL(file, error: nil)
} else {
XCTFail("file should not be nil")
}
} else {
XCTFail("contents should not be nil")
}
}
func testDownloadRequestWithProgress() {
// Given
let randomBytes = 4 * 1024 * 1024
let URLString = "http://httpbin.org/bytes/\(randomBytes)"
let fileManager = NSFileManager.defaultManager()
let directory = fileManager.URLsForDirectory(self.searchPathDirectory, inDomains: self.searchPathDomain)[0] as! NSURL
let filename = "test_download_data"
let fileURL = directory.URLByAppendingPathComponent(filename)
let expectation = expectationWithDescription("Bytes download progress should be reported: \(URLString)")
var byteValues: [(bytes: Int64, totalBytes: Int64, totalBytesExpected: Int64)] = []
var progressValues: [(completedUnitCount: Int64, totalUnitCount: Int64)] = []
var responseRequest: NSURLRequest?
var responseResponse: NSHTTPURLResponse?
var responseData: AnyObject?
var responseError: NSError?
// When
let download = Alamofire.download(.GET, URLString) { _, _ in
return fileURL
}
download.progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
let bytes = (bytes: bytesRead, totalBytes: totalBytesRead, totalBytesExpected: totalBytesExpectedToRead)
byteValues.append(bytes)
let progress = (completedUnitCount: download.progress.completedUnitCount, totalUnitCount: download.progress.totalUnitCount)
progressValues.append(progress)
}
download.response { request, response, data, error in
responseRequest = request
responseResponse = response
responseData = data
responseError = error
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(responseRequest, "response request should not be nil")
XCTAssertNotNil(responseResponse, "response response should not be nil")
XCTAssertNil(responseData, "response data should be nil")
XCTAssertNil(responseError, "response error should be nil")
XCTAssertEqual(byteValues.count, progressValues.count, "byteValues count should equal progressValues count")
if byteValues.count == progressValues.count {
for index in 0..<byteValues.count {
let byteValue = byteValues[index]
let progressValue = progressValues[index]
XCTAssertGreaterThan(byteValue.bytes, 0, "reported bytes should always be greater than 0")
XCTAssertEqual(byteValue.totalBytes, progressValue.completedUnitCount, "total bytes should be equal to completed unit count")
XCTAssertEqual(byteValue.totalBytesExpected, progressValue.totalUnitCount, "total bytes expected should be equal to total unit count")
}
}
if let lastByteValue = byteValues.last,
lastProgressValue = progressValues.last
{
let byteValueFractionalCompletion = Double(lastByteValue.totalBytes) / Double(lastByteValue.totalBytesExpected)
let progressValueFractionalCompletion = Double(lastProgressValue.0) / Double(lastProgressValue.1)
XCTAssertEqual(byteValueFractionalCompletion, 1.0, "byte value fractional completion should equal 1.0")
XCTAssertEqual(progressValueFractionalCompletion, 1.0, "progress value fractional completion should equal 1.0")
} else {
XCTFail("last item in bytesValues and progressValues should not be nil")
}
var removalError: NSError?
fileManager.removeItemAtURL(fileURL, error: &removalError)
XCTAssertNil(removalError, "removal error should be nil")
}
}
| @@ -97,27 +97,41 @@ class DownloadResponseTestCase: BaseTestCase {
}
}
- func testDownloadRequestWithProgress() {
+ func testDownloadRequestWithProgress2() { | Tests/DownloadTests.swift | 0 | Swift | 0.071 | suggestion | 45 | 177 | 177 | false | Created more robust data, upload and download progress tests | 494 | Alamofire/Alamofire | 41,690 | Swift | cnoon | cnoon |
// Alamofire.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
/**
HTTP method definitions.
See http://tools.ietf.org/html/rfc7231#section-4.3
*/
public enum Method: String {
case OPTIONS = "OPTIONS"
case GET = "GET"
case HEAD = "HEAD"
case POST = "POST"
case PUT = "PUT"
case PATCH = "PATCH"
case DELETE = "DELETE"
case TRACE = "TRACE"
case CONNECT = "CONNECT"
}
// MARK: - ParameterEncoding
/**
Used to specify the way in which a set of parameters are applied to a URL request.
*/
public enum ParameterEncoding {
/**
A query string to be set as or appended to any existing URL query for `GET`, `HEAD`, and `DELETE` requests, or set as the body for requests with any other HTTP method. The `Content-Type` HTTP header field of an encoded request with HTTP body is set to `application/x-www-form-urlencoded`. Since there is no published specification for how to encode collection types, the convention of appending `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for nested dictionary values (`foo[bar]=baz`).
*/
case URL
/**
Uses `NSJSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`.
*/
case JSON
/**
Uses `NSPropertyListSerialization` to create a plist representation of the parameters object, according to the associated format and write options values, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/x-plist`.
*/
case PropertyList(NSPropertyListFormat, NSPropertyListWriteOptions)
/**
Uses the associated closure value to construct a new request given an existing request and parameters.
*/
case Custom((URLRequestConvertible, [String: AnyObject]?) -> (NSURLRequest, NSError?))
/**
Creates a URL request by encoding parameters and applying them onto an existing request.
:param: URLRequest The request to have parameters applied
:param: parameters The parameters to apply
:returns: A tuple containing the constructed request and the error that occurred during parameter encoding, if any.
*/
public func encode(URLRequest: URLRequestConvertible, parameters: [String: AnyObject]?) -> (NSURLRequest, NSError?) {
if parameters == nil {
return (URLRequest.URLRequest, nil)
}
var mutableURLRequest: NSMutableURLRequest! = URLRequest.URLRequest.mutableCopy() as! NSMutableURLRequest
var error: NSError? = nil
switch self {
case .URL:
func query(parameters: [String: AnyObject]) -> String {
var components: [(String, String)] = []
for key in sorted(Array(parameters.keys), <) {
let value: AnyObject! = parameters[key]
components += self.queryComponents(key, value)
}
return join("&", components.map{"\($0)=\($1)"} as [String])
}
func encodesParametersInURL(method: Method) -> Bool {
switch method {
case .GET, .HEAD, .DELETE:
return true
default:
return false
}
}
let method = Method(rawValue: mutableURLRequest.HTTPMethod)
if method != nil && encodesParametersInURL(method!) {
if let URLComponents = NSURLComponents(URL: mutableURLRequest.URL!, resolvingAgainstBaseURL: false) {
URLComponents.percentEncodedQuery = (URLComponents.percentEncodedQuery != nil ? URLComponents.percentEncodedQuery! + "&" : "") + query(parameters!)
mutableURLRequest.URL = URLComponents.URL
}
} else {
if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil {
mutableURLRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
}
mutableURLRequest.HTTPBody = query(parameters!).dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
}
case .JSON:
let options = NSJSONWritingOptions.allZeros
if let data = NSJSONSerialization.dataWithJSONObject(parameters!, options: options, error: &error) {
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
mutableURLRequest.HTTPBody = data
}
case .PropertyList(let (format, options)):
if let data = NSPropertyListSerialization.dataWithPropertyList(parameters!, format: format, options: options, error: &error) {
mutableURLRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type")
mutableURLRequest.HTTPBody = data
}
case .Custom(let closure):
return closure(mutableURLRequest, parameters)
}
return (mutableURLRequest, error)
}
func queryComponents(key: String, _ value: AnyObject) -> [(String, String)] {
var components: [(String, String)] = []
if let dictionary = value as? [String: AnyObject] {
for (nestedKey, value) in dictionary {
components += queryComponents("\(key)[\(nestedKey)]", value)
}
} else if let array = value as? [AnyObject] {
for value in array {
components += queryComponents("\(key)[]", value)
}
} else {
components.extend([(escape(key), escape("\(value)"))])
}
return components
}
func escape(string: String) -> String {
let generalDelimiters = ":#[]@" // dropping "?" and "/" due to RFC 3986 - Section 3.4
let subDelimiters = "!$&'()*+,;="
let legalURLCharactersToBeEscaped: CFStringRef = generalDelimiters + subDelimiters
return CFURLCreateStringByAddingPercentEscapes(nil, string, nil, legalURLCharactersToBeEscaped, CFStringBuiltInEncodings.UTF8.rawValue) as String
}
}
| Is it worth having the comment there about dropping? May just want to add it to the release notes.
| // Alamofire.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
/**
HTTP method definitions.
See http://tools.ietf.org/html/rfc7231#section-4.3
*/
public enum Method: String {
case OPTIONS = "OPTIONS"
case GET = "GET"
case HEAD = "HEAD"
case POST = "POST"
case PUT = "PUT"
case PATCH = "PATCH"
case DELETE = "DELETE"
case TRACE = "TRACE"
case CONNECT = "CONNECT"
}
// MARK: - ParameterEncoding
/**
Used to specify the way in which a set of parameters are applied to a URL request.
*/
public enum ParameterEncoding {
/**
A query string to be set as or appended to any existing URL query for `GET`, `HEAD`, and `DELETE` requests, or set as the body for requests with any other HTTP method. The `Content-Type` HTTP header field of an encoded request with HTTP body is set to `application/x-www-form-urlencoded`. Since there is no published specification for how to encode collection types, the convention of appending `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for nested dictionary values (`foo[bar]=baz`).
*/
case URL
/**
Uses `NSJSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`.
*/
case JSON
/**
Uses `NSPropertyListSerialization` to create a plist representation of the parameters object, according to the associated format and write options values, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/x-plist`.
*/
case PropertyList(NSPropertyListFormat, NSPropertyListWriteOptions)
/**
Uses the associated closure value to construct a new request given an existing request and parameters.
*/
case Custom((URLRequestConvertible, [String: AnyObject]?) -> (NSURLRequest, NSError?))
/**
Creates a URL request by encoding parameters and applying them onto an existing request.
:param: URLRequest The request to have parameters applied
:param: parameters The parameters to apply
:returns: A tuple containing the constructed request and the error that occurred during parameter encoding, if any.
*/
public func encode(URLRequest: URLRequestConvertible, parameters: [String: AnyObject]?) -> (NSURLRequest, NSError?) {
if parameters == nil {
return (URLRequest.URLRequest, nil)
}
var mutableURLRequest: NSMutableURLRequest! = URLRequest.URLRequest.mutableCopy() as! NSMutableURLRequest
var error: NSError? = nil
switch self {
case .URL:
func query(parameters: [String: AnyObject]) -> String {
var components: [(String, String)] = []
for key in sorted(Array(parameters.keys), <) {
let value: AnyObject! = parameters[key]
components += self.queryComponents(key, value)
}
return join("&", components.map{"\($0)=\($1)"} as [String])
}
func encodesParametersInURL(method: Method) -> Bool {
switch method {
case .GET, .HEAD, .DELETE:
return true
default:
return false
}
}
let method = Method(rawValue: mutableURLRequest.HTTPMethod)
if method != nil && encodesParametersInURL(method!) {
if let URLComponents = NSURLComponents(URL: mutableURLRequest.URL!, resolvingAgainstBaseURL: false) {
URLComponents.percentEncodedQuery = (URLComponents.percentEncodedQuery != nil ? URLComponents.percentEncodedQuery! + "&" : "") + query(parameters!)
mutableURLRequest.URL = URLComponents.URL
}
} else {
if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil {
mutableURLRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
}
mutableURLRequest.HTTPBody = query(parameters!).dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
}
case .JSON:
let options = NSJSONWritingOptions.allZeros
if let data = NSJSONSerialization.dataWithJSONObject(parameters!, options: options, error: &error) {
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
mutableURLRequest.HTTPBody = data
}
case .PropertyList(let (format, options)):
if let data = NSPropertyListSerialization.dataWithPropertyList(parameters!, format: format, options: options, error: &error) {
mutableURLRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type")
mutableURLRequest.HTTPBody = data
}
case .Custom(let closure):
return closure(mutableURLRequest, parameters)
}
return (mutableURLRequest, error)
}
func queryComponents(key: String, _ value: AnyObject) -> [(String, String)] {
var components: [(String, String)] = []
if let dictionary = value as? [String: AnyObject] {
for (nestedKey, value) in dictionary {
components += queryComponents("\(key)[\(nestedKey)]", value)
}
} else if let array = value as? [AnyObject] {
for value in array {
components += queryComponents("\(key)[]", value)
}
} else {
components.extend([(escape(key), escape("\(value)"))])
}
return components
}
/**
Returns a percent escaped string following RFC 3986 for query string formatting.
RFC 3986 states that the following characters are "reserved" characters.
- General Delimiters: ":", "#", "[", "]", "@", "?", "/"
- Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
Core Foundation interprets RFC 3986 in terms of legal and illegal characters.
- Legal Numbers: "0123456789"
- Legal Letters: "abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
- Legal Characters: "!", "$", "&", "'", "(", ")", "*", "+", ",", "-",
".", "/", ":", ";", "=", "?", "@", "_", "~", "\""
- Illegal Characters: All characters not listed as Legal
While the Core Foundation `CFURLCreateStringByAddingPercentEscapes` documentation states
that it follows RFC 3986, the headers actually point out that it follows RFC 2396. This
explains why it does not consider "[", "]" and "#" to be "legal" characters even though
they are specified as "reserved" characters in RFC 3986. The following rdar has been filed
to hopefully get the documentation updated.
- https://openradar.appspot.com/radar?id=5058257274011648
In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow
query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/"
should be percent escaped in the query string.
:param: string The string to be percent escaped.
:returns: The percent escaped string.
*/
func escape(string: String) -> String {
let generalDelimiters = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
let subDelimiters = "!$&'()*+,;="
let legalURLCharactersToBeEscaped: CFStringRef = generalDelimiters + subDelimiters
return CFURLCreateStringByAddingPercentEscapes(nil, string, nil, legalURLCharactersToBeEscaped, CFStringBuiltInEncodings.UTF8.rawValue) as String
}
}
| @@ -151,7 +151,11 @@ public enum ParameterEncoding {
}
func escape(string: String) -> String {
- let legalURLCharactersToBeEscaped: CFStringRef = ":&=;+!@#$()',*"
+ let generalDelimiters = ":#[]@" // dropping "?" and "/" due to RFC 3986 - Section 3.4 | Source/ParameterEncoding.swift | 0 | Swift | 0.214 | suggestion | 99 | 162 | 194 | false | Added parameter encoding characters along with additional documentation | 504 | Alamofire/Alamofire | 41,690 | Swift | kcharwood | cnoon |
// Alamofire.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
/**
HTTP method definitions.
See http://tools.ietf.org/html/rfc7231#section-4.3
*/
public enum Method: String {
case OPTIONS = "OPTIONS"
case GET = "GET"
case HEAD = "HEAD"
case POST = "POST"
case PUT = "PUT"
case PATCH = "PATCH"
case DELETE = "DELETE"
case TRACE = "TRACE"
case CONNECT = "CONNECT"
}
// MARK: - ParameterEncoding
/**
Used to specify the way in which a set of parameters are applied to a URL request.
*/
public enum ParameterEncoding {
/**
A query string to be set as or appended to any existing URL query for `GET`, `HEAD`, and `DELETE` requests, or set as the body for requests with any other HTTP method. The `Content-Type` HTTP header field of an encoded request with HTTP body is set to `application/x-www-form-urlencoded`. Since there is no published specification for how to encode collection types, the convention of appending `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for nested dictionary values (`foo[bar]=baz`).
*/
case URL
/**
Uses `NSJSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`.
*/
case JSON
/**
Uses `NSPropertyListSerialization` to create a plist representation of the parameters object, according to the associated format and write options values, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/x-plist`.
*/
case PropertyList(NSPropertyListFormat, NSPropertyListWriteOptions)
/**
Uses the associated closure value to construct a new request given an existing request and parameters.
*/
case Custom((URLRequestConvertible, [String: AnyObject]?) -> (NSURLRequest, NSError?))
/**
Creates a URL request by encoding parameters and applying them onto an existing request.
:param: URLRequest The request to have parameters applied
:param: parameters The parameters to apply
:returns: A tuple containing the constructed request and the error that occurred during parameter encoding, if any.
*/
public func encode(URLRequest: URLRequestConvertible, parameters: [String: AnyObject]?) -> (NSURLRequest, NSError?) {
if parameters == nil {
return (URLRequest.URLRequest, nil)
}
var mutableURLRequest: NSMutableURLRequest! = URLRequest.URLRequest.mutableCopy() as! NSMutableURLRequest
var error: NSError? = nil
switch self {
case .URL:
func query(parameters: [String: AnyObject]) -> String {
var components: [(String, String)] = []
for key in sorted(Array(parameters.keys), <) {
let value: AnyObject! = parameters[key]
components += self.queryComponents(key, value)
}
return join("&", components.map{"\($0)=\($1)"} as [String])
}
func encodesParametersInURL(method: Method) -> Bool {
switch method {
case .GET, .HEAD, .DELETE:
return true
default:
return false
}
}
let method = Method(rawValue: mutableURLRequest.HTTPMethod)
if method != nil && encodesParametersInURL(method!) {
if let URLComponents = NSURLComponents(URL: mutableURLRequest.URL!, resolvingAgainstBaseURL: false) {
URLComponents.percentEncodedQuery = (URLComponents.percentEncodedQuery != nil ? URLComponents.percentEncodedQuery! + "&" : "") + query(parameters!)
mutableURLRequest.URL = URLComponents.URL
}
} else {
if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil {
mutableURLRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
}
mutableURLRequest.HTTPBody = query(parameters!).dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
}
case .JSON:
let options = NSJSONWritingOptions.allZeros
if let data = NSJSONSerialization.dataWithJSONObject(parameters!, options: options, error: &error) {
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
mutableURLRequest.HTTPBody = data
}
case .PropertyList(let (format, options)):
if let data = NSPropertyListSerialization.dataWithPropertyList(parameters!, format: format, options: options, error: &error) {
mutableURLRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type")
mutableURLRequest.HTTPBody = data
}
case .Custom(let closure):
return closure(mutableURLRequest, parameters)
}
return (mutableURLRequest, error)
}
func queryComponents(key: String, _ value: AnyObject) -> [(String, String)] {
var components: [(String, String)] = []
if let dictionary = value as? [String: AnyObject] {
for (nestedKey, value) in dictionary {
components += queryComponents("\(key)[\(nestedKey)]", value)
}
} else if let array = value as? [AnyObject] {
for value in array {
components += queryComponents("\(key)[]", value)
}
} else {
components.extend([(escape(key), escape("\(value)"))])
}
return components
}
func escape(string: String) -> String {
let generalDelimiters = ":#[]@" // dropping "?" and "/" due to RFC 3986 - Section 3.4
let subDelimiters = "!$&'()*+,;="
let legalURLCharactersToBeEscaped: CFStringRef = generalDelimiters + subDelimiters
return CFURLCreateStringByAddingPercentEscapes(nil, string, nil, legalURLCharactersToBeEscaped, CFStringBuiltInEncodings.UTF8.rawValue) as String
}
}
| Also, is it worth adding any specific tests for the square brackets?
| // Alamofire.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
/**
HTTP method definitions.
See http://tools.ietf.org/html/rfc7231#section-4.3
*/
public enum Method: String {
case OPTIONS = "OPTIONS"
case GET = "GET"
case HEAD = "HEAD"
case POST = "POST"
case PUT = "PUT"
case PATCH = "PATCH"
case DELETE = "DELETE"
case TRACE = "TRACE"
case CONNECT = "CONNECT"
}
// MARK: - ParameterEncoding
/**
Used to specify the way in which a set of parameters are applied to a URL request.
*/
public enum ParameterEncoding {
/**
A query string to be set as or appended to any existing URL query for `GET`, `HEAD`, and `DELETE` requests, or set as the body for requests with any other HTTP method. The `Content-Type` HTTP header field of an encoded request with HTTP body is set to `application/x-www-form-urlencoded`. Since there is no published specification for how to encode collection types, the convention of appending `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for nested dictionary values (`foo[bar]=baz`).
*/
case URL
/**
Uses `NSJSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`.
*/
case JSON
/**
Uses `NSPropertyListSerialization` to create a plist representation of the parameters object, according to the associated format and write options values, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/x-plist`.
*/
case PropertyList(NSPropertyListFormat, NSPropertyListWriteOptions)
/**
Uses the associated closure value to construct a new request given an existing request and parameters.
*/
case Custom((URLRequestConvertible, [String: AnyObject]?) -> (NSURLRequest, NSError?))
/**
Creates a URL request by encoding parameters and applying them onto an existing request.
:param: URLRequest The request to have parameters applied
:param: parameters The parameters to apply
:returns: A tuple containing the constructed request and the error that occurred during parameter encoding, if any.
*/
public func encode(URLRequest: URLRequestConvertible, parameters: [String: AnyObject]?) -> (NSURLRequest, NSError?) {
if parameters == nil {
return (URLRequest.URLRequest, nil)
}
var mutableURLRequest: NSMutableURLRequest! = URLRequest.URLRequest.mutableCopy() as! NSMutableURLRequest
var error: NSError? = nil
switch self {
case .URL:
func query(parameters: [String: AnyObject]) -> String {
var components: [(String, String)] = []
for key in sorted(Array(parameters.keys), <) {
let value: AnyObject! = parameters[key]
components += self.queryComponents(key, value)
}
return join("&", components.map{"\($0)=\($1)"} as [String])
}
func encodesParametersInURL(method: Method) -> Bool {
switch method {
case .GET, .HEAD, .DELETE:
return true
default:
return false
}
}
let method = Method(rawValue: mutableURLRequest.HTTPMethod)
if method != nil && encodesParametersInURL(method!) {
if let URLComponents = NSURLComponents(URL: mutableURLRequest.URL!, resolvingAgainstBaseURL: false) {
URLComponents.percentEncodedQuery = (URLComponents.percentEncodedQuery != nil ? URLComponents.percentEncodedQuery! + "&" : "") + query(parameters!)
mutableURLRequest.URL = URLComponents.URL
}
} else {
if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil {
mutableURLRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
}
mutableURLRequest.HTTPBody = query(parameters!).dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
}
case .JSON:
let options = NSJSONWritingOptions.allZeros
if let data = NSJSONSerialization.dataWithJSONObject(parameters!, options: options, error: &error) {
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
mutableURLRequest.HTTPBody = data
}
case .PropertyList(let (format, options)):
if let data = NSPropertyListSerialization.dataWithPropertyList(parameters!, format: format, options: options, error: &error) {
mutableURLRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type")
mutableURLRequest.HTTPBody = data
}
case .Custom(let closure):
return closure(mutableURLRequest, parameters)
}
return (mutableURLRequest, error)
}
func queryComponents(key: String, _ value: AnyObject) -> [(String, String)] {
var components: [(String, String)] = []
if let dictionary = value as? [String: AnyObject] {
for (nestedKey, value) in dictionary {
components += queryComponents("\(key)[\(nestedKey)]", value)
}
} else if let array = value as? [AnyObject] {
for value in array {
components += queryComponents("\(key)[]", value)
}
} else {
components.extend([(escape(key), escape("\(value)"))])
}
return components
}
/**
Returns a percent escaped string following RFC 3986 for query string formatting.
RFC 3986 states that the following characters are "reserved" characters.
- General Delimiters: ":", "#", "[", "]", "@", "?", "/"
- Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
Core Foundation interprets RFC 3986 in terms of legal and illegal characters.
- Legal Numbers: "0123456789"
- Legal Letters: "abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
- Legal Characters: "!", "$", "&", "'", "(", ")", "*", "+", ",", "-",
".", "/", ":", ";", "=", "?", "@", "_", "~", "\""
- Illegal Characters: All characters not listed as Legal
While the Core Foundation `CFURLCreateStringByAddingPercentEscapes` documentation states
that it follows RFC 3986, the headers actually point out that it follows RFC 2396. This
explains why it does not consider "[", "]" and "#" to be "legal" characters even though
they are specified as "reserved" characters in RFC 3986. The following rdar has been filed
to hopefully get the documentation updated.
- https://openradar.appspot.com/radar?id=5058257274011648
In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow
query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/"
should be percent escaped in the query string.
:param: string The string to be percent escaped.
:returns: The percent escaped string.
*/
func escape(string: String) -> String {
let generalDelimiters = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
let subDelimiters = "!$&'()*+,;="
let legalURLCharactersToBeEscaped: CFStringRef = generalDelimiters + subDelimiters
return CFURLCreateStringByAddingPercentEscapes(nil, string, nil, legalURLCharactersToBeEscaped, CFStringBuiltInEncodings.UTF8.rawValue) as String
}
}
| @@ -151,7 +151,11 @@ public enum ParameterEncoding {
}
func escape(string: String) -> String {
- let legalURLCharactersToBeEscaped: CFStringRef = ":&=;+!@#$()',*"
+ let generalDelimiters = ":#[]@" // dropping "?" and "/" due to RFC 3986 - Section 3.4 | Source/ParameterEncoding.swift | 0 | Swift | 0.214 | question | 69 | 162 | 194 | false | Added parameter encoding characters along with additional documentation | 504 | Alamofire/Alamofire | 41,690 | Swift | kcharwood | cnoon |
// Alamofire.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
/**
HTTP method definitions.
See http://tools.ietf.org/html/rfc7231#section-4.3
*/
public enum Method: String {
case OPTIONS = "OPTIONS"
case GET = "GET"
case HEAD = "HEAD"
case POST = "POST"
case PUT = "PUT"
case PATCH = "PATCH"
case DELETE = "DELETE"
case TRACE = "TRACE"
case CONNECT = "CONNECT"
}
// MARK: - ParameterEncoding
/**
Used to specify the way in which a set of parameters are applied to a URL request.
*/
public enum ParameterEncoding {
/**
A query string to be set as or appended to any existing URL query for `GET`, `HEAD`, and `DELETE` requests, or set as the body for requests with any other HTTP method. The `Content-Type` HTTP header field of an encoded request with HTTP body is set to `application/x-www-form-urlencoded`. Since there is no published specification for how to encode collection types, the convention of appending `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for nested dictionary values (`foo[bar]=baz`).
*/
case URL
/**
Uses `NSJSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`.
*/
case JSON
/**
Uses `NSPropertyListSerialization` to create a plist representation of the parameters object, according to the associated format and write options values, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/x-plist`.
*/
case PropertyList(NSPropertyListFormat, NSPropertyListWriteOptions)
/**
Uses the associated closure value to construct a new request given an existing request and parameters.
*/
case Custom((URLRequestConvertible, [String: AnyObject]?) -> (NSURLRequest, NSError?))
/**
Creates a URL request by encoding parameters and applying them onto an existing request.
:param: URLRequest The request to have parameters applied
:param: parameters The parameters to apply
:returns: A tuple containing the constructed request and the error that occurred during parameter encoding, if any.
*/
public func encode(URLRequest: URLRequestConvertible, parameters: [String: AnyObject]?) -> (NSURLRequest, NSError?) {
if parameters == nil {
return (URLRequest.URLRequest, nil)
}
var mutableURLRequest: NSMutableURLRequest! = URLRequest.URLRequest.mutableCopy() as! NSMutableURLRequest
var error: NSError? = nil
switch self {
case .URL:
func query(parameters: [String: AnyObject]) -> String {
var components: [(String, String)] = []
for key in sorted(Array(parameters.keys), <) {
let value: AnyObject! = parameters[key]
components += self.queryComponents(key, value)
}
return join("&", components.map{"\($0)=\($1)"} as [String])
}
func encodesParametersInURL(method: Method) -> Bool {
switch method {
case .GET, .HEAD, .DELETE:
return true
default:
return false
}
}
let method = Method(rawValue: mutableURLRequest.HTTPMethod)
if method != nil && encodesParametersInURL(method!) {
if let URLComponents = NSURLComponents(URL: mutableURLRequest.URL!, resolvingAgainstBaseURL: false) {
URLComponents.percentEncodedQuery = (URLComponents.percentEncodedQuery != nil ? URLComponents.percentEncodedQuery! + "&" : "") + query(parameters!)
mutableURLRequest.URL = URLComponents.URL
}
} else {
if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil {
mutableURLRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
}
mutableURLRequest.HTTPBody = query(parameters!).dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
}
case .JSON:
let options = NSJSONWritingOptions.allZeros
if let data = NSJSONSerialization.dataWithJSONObject(parameters!, options: options, error: &error) {
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
mutableURLRequest.HTTPBody = data
}
case .PropertyList(let (format, options)):
if let data = NSPropertyListSerialization.dataWithPropertyList(parameters!, format: format, options: options, error: &error) {
mutableURLRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type")
mutableURLRequest.HTTPBody = data
}
case .Custom(let closure):
return closure(mutableURLRequest, parameters)
}
return (mutableURLRequest, error)
}
func queryComponents(key: String, _ value: AnyObject) -> [(String, String)] {
var components: [(String, String)] = []
if let dictionary = value as? [String: AnyObject] {
for (nestedKey, value) in dictionary {
components += queryComponents("\(key)[\(nestedKey)]", value)
}
} else if let array = value as? [AnyObject] {
for value in array {
components += queryComponents("\(key)[]", value)
}
} else {
components.extend([(escape(key), escape("\(value)"))])
}
return components
}
func escape(string: String) -> String {
let generalDelimiters = ":#[]@" // dropping "?" and "/" due to RFC 3986 - Section 3.4
let subDelimiters = "!$&'()*+,;="
let legalURLCharactersToBeEscaped: CFStringRef = generalDelimiters + subDelimiters
return CFURLCreateStringByAddingPercentEscapes(nil, string, nil, legalURLCharactersToBeEscaped, CFStringBuiltInEncodings.UTF8.rawValue) as String
}
}
| We already have a bunch of tests around the square brackets cases, so we should be good there. As for removing the comment, I'm cool with taking it out if you think it's not great to have it in there. I want to make sure we have it documented why we shouldn't have the "?" and "/" listed as general delimiters. I'm afraid I might not remember ole RFC 3986 - Section 3.4 to the letter in 6 months. 😔
| // Alamofire.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
/**
HTTP method definitions.
See http://tools.ietf.org/html/rfc7231#section-4.3
*/
public enum Method: String {
case OPTIONS = "OPTIONS"
case GET = "GET"
case HEAD = "HEAD"
case POST = "POST"
case PUT = "PUT"
case PATCH = "PATCH"
case DELETE = "DELETE"
case TRACE = "TRACE"
case CONNECT = "CONNECT"
}
// MARK: - ParameterEncoding
/**
Used to specify the way in which a set of parameters are applied to a URL request.
*/
public enum ParameterEncoding {
/**
A query string to be set as or appended to any existing URL query for `GET`, `HEAD`, and `DELETE` requests, or set as the body for requests with any other HTTP method. The `Content-Type` HTTP header field of an encoded request with HTTP body is set to `application/x-www-form-urlencoded`. Since there is no published specification for how to encode collection types, the convention of appending `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for nested dictionary values (`foo[bar]=baz`).
*/
case URL
/**
Uses `NSJSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`.
*/
case JSON
/**
Uses `NSPropertyListSerialization` to create a plist representation of the parameters object, according to the associated format and write options values, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/x-plist`.
*/
case PropertyList(NSPropertyListFormat, NSPropertyListWriteOptions)
/**
Uses the associated closure value to construct a new request given an existing request and parameters.
*/
case Custom((URLRequestConvertible, [String: AnyObject]?) -> (NSURLRequest, NSError?))
/**
Creates a URL request by encoding parameters and applying them onto an existing request.
:param: URLRequest The request to have parameters applied
:param: parameters The parameters to apply
:returns: A tuple containing the constructed request and the error that occurred during parameter encoding, if any.
*/
public func encode(URLRequest: URLRequestConvertible, parameters: [String: AnyObject]?) -> (NSURLRequest, NSError?) {
if parameters == nil {
return (URLRequest.URLRequest, nil)
}
var mutableURLRequest: NSMutableURLRequest! = URLRequest.URLRequest.mutableCopy() as! NSMutableURLRequest
var error: NSError? = nil
switch self {
case .URL:
func query(parameters: [String: AnyObject]) -> String {
var components: [(String, String)] = []
for key in sorted(Array(parameters.keys), <) {
let value: AnyObject! = parameters[key]
components += self.queryComponents(key, value)
}
return join("&", components.map{"\($0)=\($1)"} as [String])
}
func encodesParametersInURL(method: Method) -> Bool {
switch method {
case .GET, .HEAD, .DELETE:
return true
default:
return false
}
}
let method = Method(rawValue: mutableURLRequest.HTTPMethod)
if method != nil && encodesParametersInURL(method!) {
if let URLComponents = NSURLComponents(URL: mutableURLRequest.URL!, resolvingAgainstBaseURL: false) {
URLComponents.percentEncodedQuery = (URLComponents.percentEncodedQuery != nil ? URLComponents.percentEncodedQuery! + "&" : "") + query(parameters!)
mutableURLRequest.URL = URLComponents.URL
}
} else {
if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil {
mutableURLRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
}
mutableURLRequest.HTTPBody = query(parameters!).dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
}
case .JSON:
let options = NSJSONWritingOptions.allZeros
if let data = NSJSONSerialization.dataWithJSONObject(parameters!, options: options, error: &error) {
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
mutableURLRequest.HTTPBody = data
}
case .PropertyList(let (format, options)):
if let data = NSPropertyListSerialization.dataWithPropertyList(parameters!, format: format, options: options, error: &error) {
mutableURLRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type")
mutableURLRequest.HTTPBody = data
}
case .Custom(let closure):
return closure(mutableURLRequest, parameters)
}
return (mutableURLRequest, error)
}
func queryComponents(key: String, _ value: AnyObject) -> [(String, String)] {
var components: [(String, String)] = []
if let dictionary = value as? [String: AnyObject] {
for (nestedKey, value) in dictionary {
components += queryComponents("\(key)[\(nestedKey)]", value)
}
} else if let array = value as? [AnyObject] {
for value in array {
components += queryComponents("\(key)[]", value)
}
} else {
components.extend([(escape(key), escape("\(value)"))])
}
return components
}
/**
Returns a percent escaped string following RFC 3986 for query string formatting.
RFC 3986 states that the following characters are "reserved" characters.
- General Delimiters: ":", "#", "[", "]", "@", "?", "/"
- Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
Core Foundation interprets RFC 3986 in terms of legal and illegal characters.
- Legal Numbers: "0123456789"
- Legal Letters: "abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
- Legal Characters: "!", "$", "&", "'", "(", ")", "*", "+", ",", "-",
".", "/", ":", ";", "=", "?", "@", "_", "~", "\""
- Illegal Characters: All characters not listed as Legal
While the Core Foundation `CFURLCreateStringByAddingPercentEscapes` documentation states
that it follows RFC 3986, the headers actually point out that it follows RFC 2396. This
explains why it does not consider "[", "]" and "#" to be "legal" characters even though
they are specified as "reserved" characters in RFC 3986. The following rdar has been filed
to hopefully get the documentation updated.
- https://openradar.appspot.com/radar?id=5058257274011648
In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow
query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/"
should be percent escaped in the query string.
:param: string The string to be percent escaped.
:returns: The percent escaped string.
*/
func escape(string: String) -> String {
let generalDelimiters = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
let subDelimiters = "!$&'()*+,;="
let legalURLCharactersToBeEscaped: CFStringRef = generalDelimiters + subDelimiters
return CFURLCreateStringByAddingPercentEscapes(nil, string, nil, legalURLCharactersToBeEscaped, CFStringBuiltInEncodings.UTF8.rawValue) as String
}
}
| @@ -151,7 +151,11 @@ public enum ParameterEncoding {
}
func escape(string: String) -> String {
- let legalURLCharactersToBeEscaped: CFStringRef = ":&=;+!@#$()',*"
+ let generalDelimiters = ":#[]@" // dropping "?" and "/" due to RFC 3986 - Section 3.4 | Source/ParameterEncoding.swift | 0 | Swift | 0.5 | suggestion | 399 | 162 | 194 | false | Added parameter encoding characters along with additional documentation | 504 | Alamofire/Alamofire | 41,690 | Swift | cnoon | cnoon |
// Alamofire.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
/**
HTTP method definitions.
See http://tools.ietf.org/html/rfc7231#section-4.3
*/
public enum Method: String {
case OPTIONS = "OPTIONS"
case GET = "GET"
case HEAD = "HEAD"
case POST = "POST"
case PUT = "PUT"
case PATCH = "PATCH"
case DELETE = "DELETE"
case TRACE = "TRACE"
case CONNECT = "CONNECT"
}
// MARK: - ParameterEncoding
/**
Used to specify the way in which a set of parameters are applied to a URL request.
*/
public enum ParameterEncoding {
/**
A query string to be set as or appended to any existing URL query for `GET`, `HEAD`, and `DELETE` requests, or set as the body for requests with any other HTTP method. The `Content-Type` HTTP header field of an encoded request with HTTP body is set to `application/x-www-form-urlencoded`. Since there is no published specification for how to encode collection types, the convention of appending `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for nested dictionary values (`foo[bar]=baz`).
*/
case URL
/**
Uses `NSJSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`.
*/
case JSON
/**
Uses `NSPropertyListSerialization` to create a plist representation of the parameters object, according to the associated format and write options values, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/x-plist`.
*/
case PropertyList(NSPropertyListFormat, NSPropertyListWriteOptions)
/**
Uses the associated closure value to construct a new request given an existing request and parameters.
*/
case Custom((URLRequestConvertible, [String: AnyObject]?) -> (NSURLRequest, NSError?))
/**
Creates a URL request by encoding parameters and applying them onto an existing request.
:param: URLRequest The request to have parameters applied
:param: parameters The parameters to apply
:returns: A tuple containing the constructed request and the error that occurred during parameter encoding, if any.
*/
public func encode(URLRequest: URLRequestConvertible, parameters: [String: AnyObject]?) -> (NSURLRequest, NSError?) {
if parameters == nil {
return (URLRequest.URLRequest, nil)
}
var mutableURLRequest: NSMutableURLRequest! = URLRequest.URLRequest.mutableCopy() as! NSMutableURLRequest
var error: NSError? = nil
switch self {
case .URL:
func query(parameters: [String: AnyObject]) -> String {
var components: [(String, String)] = []
for key in sorted(Array(parameters.keys), <) {
let value: AnyObject! = parameters[key]
components += self.queryComponents(key, value)
}
return join("&", components.map{"\($0)=\($1)"} as [String])
}
func encodesParametersInURL(method: Method) -> Bool {
switch method {
case .GET, .HEAD, .DELETE:
return true
default:
return false
}
}
let method = Method(rawValue: mutableURLRequest.HTTPMethod)
if method != nil && encodesParametersInURL(method!) {
if let URLComponents = NSURLComponents(URL: mutableURLRequest.URL!, resolvingAgainstBaseURL: false) {
URLComponents.percentEncodedQuery = (URLComponents.percentEncodedQuery != nil ? URLComponents.percentEncodedQuery! + "&" : "") + query(parameters!)
mutableURLRequest.URL = URLComponents.URL
}
} else {
if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil {
mutableURLRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
}
mutableURLRequest.HTTPBody = query(parameters!).dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
}
case .JSON:
let options = NSJSONWritingOptions.allZeros
if let data = NSJSONSerialization.dataWithJSONObject(parameters!, options: options, error: &error) {
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
mutableURLRequest.HTTPBody = data
}
case .PropertyList(let (format, options)):
if let data = NSPropertyListSerialization.dataWithPropertyList(parameters!, format: format, options: options, error: &error) {
mutableURLRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type")
mutableURLRequest.HTTPBody = data
}
case .Custom(let closure):
return closure(mutableURLRequest, parameters)
}
return (mutableURLRequest, error)
}
func queryComponents(key: String, _ value: AnyObject) -> [(String, String)] {
var components: [(String, String)] = []
if let dictionary = value as? [String: AnyObject] {
for (nestedKey, value) in dictionary {
components += queryComponents("\(key)[\(nestedKey)]", value)
}
} else if let array = value as? [AnyObject] {
for value in array {
components += queryComponents("\(key)[]", value)
}
} else {
components.extend([(escape(key), escape("\(value)"))])
}
return components
}
func escape(string: String) -> String {
let generalDelimiters = ":#[]@" // dropping "?" and "/" due to RFC 3986 - Section 3.4
let subDelimiters = "!$&'()*+,;="
let legalURLCharactersToBeEscaped: CFStringRef = generalDelimiters + subDelimiters
return CFURLCreateStringByAddingPercentEscapes(nil, string, nil, legalURLCharactersToBeEscaped, CFStringBuiltInEncodings.UTF8.rawValue) as String
}
}
| Ya makes sense. May be better to document why those aren't there, rather than saying "we're dropping them". "We're dropping them sounds more like a temp comment, rather than documentation expected to live there for a long time. Make sense?
And does that mean the square bracket tests were failing before this PR?
| // Alamofire.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
/**
HTTP method definitions.
See http://tools.ietf.org/html/rfc7231#section-4.3
*/
public enum Method: String {
case OPTIONS = "OPTIONS"
case GET = "GET"
case HEAD = "HEAD"
case POST = "POST"
case PUT = "PUT"
case PATCH = "PATCH"
case DELETE = "DELETE"
case TRACE = "TRACE"
case CONNECT = "CONNECT"
}
// MARK: - ParameterEncoding
/**
Used to specify the way in which a set of parameters are applied to a URL request.
*/
public enum ParameterEncoding {
/**
A query string to be set as or appended to any existing URL query for `GET`, `HEAD`, and `DELETE` requests, or set as the body for requests with any other HTTP method. The `Content-Type` HTTP header field of an encoded request with HTTP body is set to `application/x-www-form-urlencoded`. Since there is no published specification for how to encode collection types, the convention of appending `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for nested dictionary values (`foo[bar]=baz`).
*/
case URL
/**
Uses `NSJSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`.
*/
case JSON
/**
Uses `NSPropertyListSerialization` to create a plist representation of the parameters object, according to the associated format and write options values, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/x-plist`.
*/
case PropertyList(NSPropertyListFormat, NSPropertyListWriteOptions)
/**
Uses the associated closure value to construct a new request given an existing request and parameters.
*/
case Custom((URLRequestConvertible, [String: AnyObject]?) -> (NSURLRequest, NSError?))
/**
Creates a URL request by encoding parameters and applying them onto an existing request.
:param: URLRequest The request to have parameters applied
:param: parameters The parameters to apply
:returns: A tuple containing the constructed request and the error that occurred during parameter encoding, if any.
*/
public func encode(URLRequest: URLRequestConvertible, parameters: [String: AnyObject]?) -> (NSURLRequest, NSError?) {
if parameters == nil {
return (URLRequest.URLRequest, nil)
}
var mutableURLRequest: NSMutableURLRequest! = URLRequest.URLRequest.mutableCopy() as! NSMutableURLRequest
var error: NSError? = nil
switch self {
case .URL:
func query(parameters: [String: AnyObject]) -> String {
var components: [(String, String)] = []
for key in sorted(Array(parameters.keys), <) {
let value: AnyObject! = parameters[key]
components += self.queryComponents(key, value)
}
return join("&", components.map{"\($0)=\($1)"} as [String])
}
func encodesParametersInURL(method: Method) -> Bool {
switch method {
case .GET, .HEAD, .DELETE:
return true
default:
return false
}
}
let method = Method(rawValue: mutableURLRequest.HTTPMethod)
if method != nil && encodesParametersInURL(method!) {
if let URLComponents = NSURLComponents(URL: mutableURLRequest.URL!, resolvingAgainstBaseURL: false) {
URLComponents.percentEncodedQuery = (URLComponents.percentEncodedQuery != nil ? URLComponents.percentEncodedQuery! + "&" : "") + query(parameters!)
mutableURLRequest.URL = URLComponents.URL
}
} else {
if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil {
mutableURLRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
}
mutableURLRequest.HTTPBody = query(parameters!).dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
}
case .JSON:
let options = NSJSONWritingOptions.allZeros
if let data = NSJSONSerialization.dataWithJSONObject(parameters!, options: options, error: &error) {
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
mutableURLRequest.HTTPBody = data
}
case .PropertyList(let (format, options)):
if let data = NSPropertyListSerialization.dataWithPropertyList(parameters!, format: format, options: options, error: &error) {
mutableURLRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type")
mutableURLRequest.HTTPBody = data
}
case .Custom(let closure):
return closure(mutableURLRequest, parameters)
}
return (mutableURLRequest, error)
}
func queryComponents(key: String, _ value: AnyObject) -> [(String, String)] {
var components: [(String, String)] = []
if let dictionary = value as? [String: AnyObject] {
for (nestedKey, value) in dictionary {
components += queryComponents("\(key)[\(nestedKey)]", value)
}
} else if let array = value as? [AnyObject] {
for value in array {
components += queryComponents("\(key)[]", value)
}
} else {
components.extend([(escape(key), escape("\(value)"))])
}
return components
}
/**
Returns a percent escaped string following RFC 3986 for query string formatting.
RFC 3986 states that the following characters are "reserved" characters.
- General Delimiters: ":", "#", "[", "]", "@", "?", "/"
- Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
Core Foundation interprets RFC 3986 in terms of legal and illegal characters.
- Legal Numbers: "0123456789"
- Legal Letters: "abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
- Legal Characters: "!", "$", "&", "'", "(", ")", "*", "+", ",", "-",
".", "/", ":", ";", "=", "?", "@", "_", "~", "\""
- Illegal Characters: All characters not listed as Legal
While the Core Foundation `CFURLCreateStringByAddingPercentEscapes` documentation states
that it follows RFC 3986, the headers actually point out that it follows RFC 2396. This
explains why it does not consider "[", "]" and "#" to be "legal" characters even though
they are specified as "reserved" characters in RFC 3986. The following rdar has been filed
to hopefully get the documentation updated.
- https://openradar.appspot.com/radar?id=5058257274011648
In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow
query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/"
should be percent escaped in the query string.
:param: string The string to be percent escaped.
:returns: The percent escaped string.
*/
func escape(string: String) -> String {
let generalDelimiters = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
let subDelimiters = "!$&'()*+,;="
let legalURLCharactersToBeEscaped: CFStringRef = generalDelimiters + subDelimiters
return CFURLCreateStringByAddingPercentEscapes(nil, string, nil, legalURLCharactersToBeEscaped, CFStringBuiltInEncodings.UTF8.rawValue) as String
}
}
| @@ -151,7 +151,11 @@ public enum ParameterEncoding {
}
func escape(string: String) -> String {
- let legalURLCharactersToBeEscaped: CFStringRef = ":&=;+!@#$()',*"
+ let generalDelimiters = ":#[]@" // dropping "?" and "/" due to RFC 3986 - Section 3.4 | Source/ParameterEncoding.swift | 0 | Swift | 0.5 | bug | 314 | 162 | 194 | false | Added parameter encoding characters along with additional documentation | 504 | Alamofire/Alamofire | 41,690 | Swift | kcharwood | cnoon |
// CacheTests.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Alamofire
import Foundation
import XCTest
/**
This test case tests all implemented cache policies against various `Cache-Control` header values. These tests
are meant to cover the main cases of `Cache-Control` header usage, but are no means exhaustive.
These tests work as follows:
- Set up an `NSURLCache`
- Set up an `Alamofire.Manager`
- Execute requests for all `Cache-Control` headers values to prime the `NSURLCache` with cached responses
- Start up a new test
- Execute another round of the same requests with a given `NSURLRequestCachePolicy`
- Verify whether the response came from the cache or from the network
- This is determined by whether the cached response timestamp matches the new response timestamp
An important thing to note is the difference in behavior between iOS and OS X. On iOS, a response with
a `Cache-Control` header value of `no-store` is still written into the `NSURLCache` where on OS X, it is not.
The different tests below reflect and demonstrate this behavior.
For information about `Cache-Control` HTTP headers, please refer to RFC 2616 - Section 14.9.
*/
class CacheTestCase: BaseTestCase {
// MARK: -
struct CacheControl {
static let Public = "public"
static let Private = "private"
static let MaxAgeNonExpired = "max-age=3600"
static let MaxAgeExpired = "max-age=0"
static let NoCache = "no-cache"
static let NoStore = "no-store"
static var allValues: [String] {
return [
CacheControl.Public,
CacheControl.Private,
CacheControl.MaxAgeNonExpired,
CacheControl.MaxAgeExpired,
CacheControl.NoCache,
CacheControl.NoStore
]
}
}
// MARK: - Properties
var URLCache: NSURLCache!
var manager: Manager!
let URLString = "http://httpbin.org/response-headers"
let requestTimeout: NSTimeInterval = 30
var requests: [String: NSURLRequest] = [:]
var timestamps: [String: String] = [:]
// MARK: - Setup and Teardown
override func setUp() {
super.setUp()
self.URLCache = {
let capacity = 50 * 1024 * 1024 // MBs
let URLCache = NSURLCache(memoryCapacity: capacity, diskCapacity: capacity, diskPath: nil)
return URLCache
}()
self.manager = {
let configuration: NSURLSessionConfiguration = {
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.HTTPAdditionalHeaders = Alamofire.Manager.defaultHTTPHeaders
configuration.requestCachePolicy = .UseProtocolCachePolicy
configuration.URLCache = self.URLCache
return configuration
}()
let manager = Manager(configuration: configuration)
return manager
}()
primeCachedResponses()
}
override func tearDown() {
super.tearDown()
self.URLCache.removeAllCachedResponses()
}
// MARK: - Cache Priming Methods
/**
Executes a request for all `Cache-Control` header values to load the response into the `URLCache`.
This implementation leverages dispatch groups to execute all the requests as well as wait an additional
second before returning. This ensures the cache contains responses for all requests that are at least
one second old. This allows the tests to distinguish whether the subsequent responses come from the cache
or the network based on the timestamp of the response.
*/
func primeCachedResponses() {
let dispatchGroup = dispatch_group_create()
let highPriorityDispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)
for cacheControl in CacheControl.allValues {
dispatch_group_enter(dispatchGroup)
let request = self.startRequest(
cacheControl: cacheControl,
queue: highPriorityDispatchQueue,
completion: { _, response in
let timestamp = response!.allHeaderFields["Date"] as! String
self.timestamps[cacheControl] = timestamp
dispatch_group_leave(dispatchGroup)
}
)
self.requests[cacheControl] = request
}
// Wait for all requests to complete
dispatch_group_wait(dispatchGroup, dispatch_time(DISPATCH_TIME_NOW, Int64(10.0 * Float(NSEC_PER_SEC))))
// Pause for 1 additional second to ensure all timestamps will be different
dispatch_group_enter(dispatchGroup)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(1.0 * Float(NSEC_PER_SEC))), highPriorityDispatchQueue) {
dispatch_group_leave(dispatchGroup)
}
// Wait for our 1 second pause to complete
dispatch_group_wait(dispatchGroup, dispatch_time(DISPATCH_TIME_NOW, Int64(10.0 * Float(NSEC_PER_SEC))))
}
// MARK: - Request Helper Methods
func URLRequest(#cacheControl: String, cachePolicy: NSURLRequestCachePolicy) -> NSURLRequest {
let parameters = ["Cache-Control": cacheControl]
let URL = NSURL(string: self.URLString)!
let URLRequest = NSMutableURLRequest(URL: URL, cachePolicy: cachePolicy, timeoutInterval: self.requestTimeout)
URLRequest.HTTPMethod = Method.GET.rawValue
return ParameterEncoding.URL.encode(URLRequest, parameters: parameters).0
}
func startRequest(
#cacheControl: String,
cachePolicy: NSURLRequestCachePolicy = .UseProtocolCachePolicy,
queue: dispatch_queue_t = dispatch_get_main_queue(),
completion: (NSURLRequest, NSHTTPURLResponse?) -> Void)
-> NSURLRequest
{
let urlRequest = URLRequest(cacheControl: cacheControl, cachePolicy: cachePolicy)
let request = self.manager.request(urlRequest)
request.response(
queue: queue,
serializer: Request.responseDataSerializer(),
completionHandler: { _, response, _, _ in
completion(request.request, response)
}
)
return urlRequest
}
// MARK: - Test Execution and Verification
func executeTest(
#cachePolicy: NSURLRequestCachePolicy,
cacheControl: String,
shouldReturnCachedResponse: Bool)
{
// Given
let expectation = expectationWithDescription("GET request to httpbin")
var response: NSHTTPURLResponse?
// When
let request = startRequest(cacheControl: cacheControl, cachePolicy: cachePolicy) { _, responseResponse in
response = responseResponse
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
verifyResponse(response, forCacheControl: cacheControl, isCachedResponse: shouldReturnCachedResponse)
}
func verifyResponse(response: NSHTTPURLResponse?, forCacheControl cacheControl: String, isCachedResponse: Bool) {
let cachedResponseTimestamp = self.timestamps[cacheControl]!
if let
response = response,
timestamp = response.allHeaderFields["Date"] as? String
{
if isCachedResponse {
XCTAssertEqual(timestamp, cachedResponseTimestamp, "timestamps should be equal")
} else {
XCTAssertNotEqual(timestamp, cachedResponseTimestamp, "timestamps should not be equal")
}
} else {
XCTFail("response should not be nil")
}
}
// MARK: - Tests
func testURLCacheContainsCachedResponsesForAllRequests() {
// Given
let publicRequest = self.requests[CacheControl.Public]!
let privateRequest = self.requests[CacheControl.Private]!
let maxAgeNonExpiredRequest = self.requests[CacheControl.MaxAgeNonExpired]!
let maxAgeExpiredRequest = self.requests[CacheControl.MaxAgeExpired]!
let noCacheRequest = self.requests[CacheControl.NoCache]!
let noStoreRequest = self.requests[CacheControl.NoStore]!
// When
let publicResponse = self.URLCache.cachedResponseForRequest(publicRequest)
let privateResponse = self.URLCache.cachedResponseForRequest(privateRequest)
let maxAgeNonExpiredResponse = self.URLCache.cachedResponseForRequest(maxAgeNonExpiredRequest)
let maxAgeExpiredResponse = self.URLCache.cachedResponseForRequest(maxAgeExpiredRequest)
let noCacheResponse = self.URLCache.cachedResponseForRequest(noCacheRequest)
let noStoreResponse = self.URLCache.cachedResponseForRequest(noStoreRequest)
// Then
XCTAssertNotNil(publicResponse, "\(CacheControl.Public) response should not be nil")
XCTAssertNotNil(privateResponse, "\(CacheControl.Private) response should not be nil")
XCTAssertNotNil(maxAgeNonExpiredResponse, "\(CacheControl.MaxAgeNonExpired) response should not be nil")
XCTAssertNotNil(maxAgeExpiredResponse, "\(CacheControl.MaxAgeExpired) response should not be nil")
XCTAssertNotNil(noCacheResponse, "\(CacheControl.NoCache) response should not be nil")
#if os(OSX)
XCTAssertNil(noStoreResponse, "\(CacheControl.NoStore) response should be nil")
#else
XCTAssertNotNil(noStoreResponse, "\(CacheControl.NoStore) response should not be nil")
#endif
}
func testDefaultCachePolicy() {
let cachePolicy: NSURLRequestCachePolicy = .UseProtocolCachePolicy
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.Public, shouldReturnCachedResponse: false)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.Private, shouldReturnCachedResponse: false)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.MaxAgeNonExpired, shouldReturnCachedResponse: true)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.MaxAgeExpired, shouldReturnCachedResponse: false)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.NoCache, shouldReturnCachedResponse: false)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.NoStore, shouldReturnCachedResponse: false)
}
func testIgnoreLocalCacheDataPolicy() {
let cachePolicy: NSURLRequestCachePolicy = .ReloadIgnoringLocalCacheData
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.Public, shouldReturnCachedResponse: false)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.Private, shouldReturnCachedResponse: false)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.MaxAgeNonExpired, shouldReturnCachedResponse: false)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.MaxAgeExpired, shouldReturnCachedResponse: false)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.NoCache, shouldReturnCachedResponse: false)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.NoStore, shouldReturnCachedResponse: false)
}
func testUseLocalCacheDataIfExistsOtherwiseLoadFromNetworkPolicy() {
let cachePolicy: NSURLRequestCachePolicy = .ReturnCacheDataElseLoad
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.Public, shouldReturnCachedResponse: true)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.Private, shouldReturnCachedResponse: true)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.MaxAgeNonExpired, shouldReturnCachedResponse: true)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.MaxAgeExpired, shouldReturnCachedResponse: true)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.NoCache, shouldReturnCachedResponse: true)
#if os(OSX)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.NoStore, shouldReturnCachedResponse: false)
#else
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.NoStore, shouldReturnCachedResponse: true)
#endif
}
func testUseLocalCacheDataAndDontLoadFromNetworkPolicy() {
let cachePolicy: NSURLRequestCachePolicy = .ReturnCacheDataDontLoad
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.Public, shouldReturnCachedResponse: true)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.Private, shouldReturnCachedResponse: true)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.MaxAgeNonExpired, shouldReturnCachedResponse: true)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.MaxAgeExpired, shouldReturnCachedResponse: true)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.NoCache, shouldReturnCachedResponse: true)
#if os(OSX)
// Given
let expectation = expectationWithDescription("GET request to httpbin")
var response: NSHTTPURLResponse?
// When
let request = startRequest(cacheControl: CacheControl.NoStore, cachePolicy: cachePolicy) { _, responseResponse in
response = responseResponse
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNil(response, "response should be nil")
#else
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.NoStore, shouldReturnCachedResponse: true)
#endif
}
}
| Can you explain the difference between OS X and iOS?
| // CacheTests.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Alamofire
import Foundation
import XCTest
/**
This test case tests all implemented cache policies against various `Cache-Control` header values. These tests
are meant to cover the main cases of `Cache-Control` header usage, but are no means exhaustive.
These tests work as follows:
- Set up an `NSURLCache`
- Set up an `Alamofire.Manager`
- Execute requests for all `Cache-Control` headers values to prime the `NSURLCache` with cached responses
- Start up a new test
- Execute another round of the same requests with a given `NSURLRequestCachePolicy`
- Verify whether the response came from the cache or from the network
- This is determined by whether the cached response timestamp matches the new response timestamp
An important thing to note is the difference in behavior between iOS and OS X. On iOS, a response with
a `Cache-Control` header value of `no-store` is still written into the `NSURLCache` where on OS X, it is not.
The different tests below reflect and demonstrate this behavior.
For information about `Cache-Control` HTTP headers, please refer to RFC 2616 - Section 14.9.
*/
class CacheTestCase: BaseTestCase {
// MARK: -
struct CacheControl {
static let Public = "public"
static let Private = "private"
static let MaxAgeNonExpired = "max-age=3600"
static let MaxAgeExpired = "max-age=0"
static let NoCache = "no-cache"
static let NoStore = "no-store"
static var allValues: [String] {
return [
CacheControl.Public,
CacheControl.Private,
CacheControl.MaxAgeNonExpired,
CacheControl.MaxAgeExpired,
CacheControl.NoCache,
CacheControl.NoStore
]
}
}
// MARK: - Properties
var URLCache: NSURLCache!
var manager: Manager!
let URLString = "http://httpbin.org/response-headers"
let requestTimeout: NSTimeInterval = 30
var requests: [String: NSURLRequest] = [:]
var timestamps: [String: String] = [:]
// MARK: - Setup and Teardown
override func setUp() {
super.setUp()
self.URLCache = {
let capacity = 50 * 1024 * 1024 // MBs
let URLCache = NSURLCache(memoryCapacity: capacity, diskCapacity: capacity, diskPath: nil)
return URLCache
}()
self.manager = {
let configuration: NSURLSessionConfiguration = {
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.HTTPAdditionalHeaders = Alamofire.Manager.defaultHTTPHeaders
configuration.requestCachePolicy = .UseProtocolCachePolicy
configuration.URLCache = self.URLCache
return configuration
}()
let manager = Manager(configuration: configuration)
return manager
}()
primeCachedResponses()
}
override func tearDown() {
super.tearDown()
self.URLCache.removeAllCachedResponses()
}
// MARK: - Cache Priming Methods
/**
Executes a request for all `Cache-Control` header values to load the response into the `URLCache`.
This implementation leverages dispatch groups to execute all the requests as well as wait an additional
second before returning. This ensures the cache contains responses for all requests that are at least
one second old. This allows the tests to distinguish whether the subsequent responses come from the cache
or the network based on the timestamp of the response.
*/
func primeCachedResponses() {
let dispatchGroup = dispatch_group_create()
let highPriorityDispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)
for cacheControl in CacheControl.allValues {
dispatch_group_enter(dispatchGroup)
let request = self.startRequest(
cacheControl: cacheControl,
queue: highPriorityDispatchQueue,
completion: { _, response in
let timestamp = response!.allHeaderFields["Date"] as! String
self.timestamps[cacheControl] = timestamp
dispatch_group_leave(dispatchGroup)
}
)
self.requests[cacheControl] = request
}
// Wait for all requests to complete
dispatch_group_wait(dispatchGroup, dispatch_time(DISPATCH_TIME_NOW, Int64(10.0 * Float(NSEC_PER_SEC))))
// Pause for 1 additional second to ensure all timestamps will be different
dispatch_group_enter(dispatchGroup)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(1.0 * Float(NSEC_PER_SEC))), highPriorityDispatchQueue) {
dispatch_group_leave(dispatchGroup)
}
// Wait for our 1 second pause to complete
dispatch_group_wait(dispatchGroup, dispatch_time(DISPATCH_TIME_NOW, Int64(10.0 * Float(NSEC_PER_SEC))))
}
// MARK: - Request Helper Methods
func URLRequest(#cacheControl: String, cachePolicy: NSURLRequestCachePolicy) -> NSURLRequest {
let parameters = ["Cache-Control": cacheControl]
let URL = NSURL(string: self.URLString)!
let URLRequest = NSMutableURLRequest(URL: URL, cachePolicy: cachePolicy, timeoutInterval: self.requestTimeout)
URLRequest.HTTPMethod = Method.GET.rawValue
return ParameterEncoding.URL.encode(URLRequest, parameters: parameters).0
}
func startRequest(
#cacheControl: String,
cachePolicy: NSURLRequestCachePolicy = .UseProtocolCachePolicy,
queue: dispatch_queue_t = dispatch_get_main_queue(),
completion: (NSURLRequest, NSHTTPURLResponse?) -> Void)
-> NSURLRequest
{
let urlRequest = URLRequest(cacheControl: cacheControl, cachePolicy: cachePolicy)
let request = self.manager.request(urlRequest)
request.response(
queue: queue,
serializer: Request.responseDataSerializer(),
completionHandler: { _, response, _, _ in
completion(request.request, response)
}
)
return urlRequest
}
// MARK: - Test Execution and Verification
func executeTest(
#cachePolicy: NSURLRequestCachePolicy,
cacheControl: String,
shouldReturnCachedResponse: Bool)
{
// Given
let expectation = expectationWithDescription("GET request to httpbin")
var response: NSHTTPURLResponse?
// When
let request = startRequest(cacheControl: cacheControl, cachePolicy: cachePolicy) { _, responseResponse in
response = responseResponse
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
verifyResponse(response, forCacheControl: cacheControl, isCachedResponse: shouldReturnCachedResponse)
}
func verifyResponse(response: NSHTTPURLResponse?, forCacheControl cacheControl: String, isCachedResponse: Bool) {
let cachedResponseTimestamp = self.timestamps[cacheControl]!
if let
response = response,
timestamp = response.allHeaderFields["Date"] as? String
{
if isCachedResponse {
XCTAssertEqual(timestamp, cachedResponseTimestamp, "timestamps should be equal")
} else {
XCTAssertNotEqual(timestamp, cachedResponseTimestamp, "timestamps should not be equal")
}
} else {
XCTFail("response should not be nil")
}
}
// MARK: - Tests
func testURLCacheContainsCachedResponsesForAllRequests() {
// Given
let publicRequest = self.requests[CacheControl.Public]!
let privateRequest = self.requests[CacheControl.Private]!
let maxAgeNonExpiredRequest = self.requests[CacheControl.MaxAgeNonExpired]!
let maxAgeExpiredRequest = self.requests[CacheControl.MaxAgeExpired]!
let noCacheRequest = self.requests[CacheControl.NoCache]!
let noStoreRequest = self.requests[CacheControl.NoStore]!
// When
let publicResponse = self.URLCache.cachedResponseForRequest(publicRequest)
let privateResponse = self.URLCache.cachedResponseForRequest(privateRequest)
let maxAgeNonExpiredResponse = self.URLCache.cachedResponseForRequest(maxAgeNonExpiredRequest)
let maxAgeExpiredResponse = self.URLCache.cachedResponseForRequest(maxAgeExpiredRequest)
let noCacheResponse = self.URLCache.cachedResponseForRequest(noCacheRequest)
let noStoreResponse = self.URLCache.cachedResponseForRequest(noStoreRequest)
// Then
XCTAssertNotNil(publicResponse, "\(CacheControl.Public) response should not be nil")
XCTAssertNotNil(privateResponse, "\(CacheControl.Private) response should not be nil")
XCTAssertNotNil(maxAgeNonExpiredResponse, "\(CacheControl.MaxAgeNonExpired) response should not be nil")
XCTAssertNotNil(maxAgeExpiredResponse, "\(CacheControl.MaxAgeExpired) response should not be nil")
XCTAssertNotNil(noCacheResponse, "\(CacheControl.NoCache) response should not be nil")
XCTAssertNil(noStoreResponse, "\(CacheControl.NoStore) response should be nil")
}
func testDefaultCachePolicy() {
let cachePolicy: NSURLRequestCachePolicy = .UseProtocolCachePolicy
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.Public, shouldReturnCachedResponse: false)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.Private, shouldReturnCachedResponse: false)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.MaxAgeNonExpired, shouldReturnCachedResponse: true)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.MaxAgeExpired, shouldReturnCachedResponse: false)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.NoCache, shouldReturnCachedResponse: false)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.NoStore, shouldReturnCachedResponse: false)
}
func testIgnoreLocalCacheDataPolicy() {
let cachePolicy: NSURLRequestCachePolicy = .ReloadIgnoringLocalCacheData
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.Public, shouldReturnCachedResponse: false)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.Private, shouldReturnCachedResponse: false)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.MaxAgeNonExpired, shouldReturnCachedResponse: false)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.MaxAgeExpired, shouldReturnCachedResponse: false)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.NoCache, shouldReturnCachedResponse: false)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.NoStore, shouldReturnCachedResponse: false)
}
func testUseLocalCacheDataIfExistsOtherwiseLoadFromNetworkPolicy() {
let cachePolicy: NSURLRequestCachePolicy = .ReturnCacheDataElseLoad
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.Public, shouldReturnCachedResponse: true)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.Private, shouldReturnCachedResponse: true)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.MaxAgeNonExpired, shouldReturnCachedResponse: true)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.MaxAgeExpired, shouldReturnCachedResponse: true)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.NoCache, shouldReturnCachedResponse: true)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.NoStore, shouldReturnCachedResponse: false)
}
func testUseLocalCacheDataAndDontLoadFromNetworkPolicy() {
let cachePolicy: NSURLRequestCachePolicy = .ReturnCacheDataDontLoad
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.Public, shouldReturnCachedResponse: true)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.Private, shouldReturnCachedResponse: true)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.MaxAgeNonExpired, shouldReturnCachedResponse: true)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.MaxAgeExpired, shouldReturnCachedResponse: true)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.NoCache, shouldReturnCachedResponse: true)
// Execute Test - CacheControl.NoStore
// Given
let expectation = expectationWithDescription("GET request to httpbin")
var response: NSHTTPURLResponse?
// When
let request = startRequest(cacheControl: CacheControl.NoStore, cachePolicy: cachePolicy) { _, responseResponse in
response = responseResponse
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNil(response, "response should be nil")
}
}
| @@ -0,0 +1,333 @@
+// CacheTests.swift
+//
+// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+import Alamofire
+import Foundation
+import XCTest
+
+/**
+ This test case tests all implemented cache policies against various `Cache-Control` header values. These tests
+ are meant to cover the main cases of `Cache-Control` header usage, but are no means exhaustive.
+
+ These tests work as follows:
+
+ - Set up an `NSURLCache`
+ - Set up an `Alamofire.Manager`
+ - Execute requests for all `Cache-Control` headers values to prime the `NSURLCache` with cached responses
+ - Start up a new test
+ - Execute another round of the same requests with a given `NSURLRequestCachePolicy`
+ - Verify whether the response came from the cache or from the network
+ - This is determined by whether the cached response timestamp matches the new response timestamp
+
+ An important thing to note is the difference in behavior between iOS and OS X. On iOS, a response with
+ a `Cache-Control` header value of `no-store` is still written into the `NSURLCache` where on OS X, it is not.
+ The different tests below reflect and demonstrate this behavior.
+
+ For information about `Cache-Control` HTTP headers, please refer to RFC 2616 - Section 14.9.
+*/
+class CacheTestCase: BaseTestCase {
+
+ // MARK: -
+
+ struct CacheControl {
+ static let Public = "public"
+ static let Private = "private"
+ static let MaxAgeNonExpired = "max-age=3600"
+ static let MaxAgeExpired = "max-age=0"
+ static let NoCache = "no-cache"
+ static let NoStore = "no-store"
+
+ static var allValues: [String] {
+ return [
+ CacheControl.Public,
+ CacheControl.Private,
+ CacheControl.MaxAgeNonExpired,
+ CacheControl.MaxAgeExpired,
+ CacheControl.NoCache,
+ CacheControl.NoStore
+ ]
+ }
+ }
+
+ // MARK: - Properties
+
+ var URLCache: NSURLCache!
+ var manager: Manager!
+
+ let URLString = "http://httpbin.org/response-headers"
+ let requestTimeout: NSTimeInterval = 30
+
+ var requests: [String: NSURLRequest] = [:]
+ var timestamps: [String: String] = [:]
+
+ // MARK: - Setup and Teardown
+
+ override func setUp() {
+ super.setUp()
+
+ self.URLCache = {
+ let capacity = 50 * 1024 * 1024 // MBs
+ let URLCache = NSURLCache(memoryCapacity: capacity, diskCapacity: capacity, diskPath: nil)
+
+ return URLCache
+ }()
+
+ self.manager = {
+ let configuration: NSURLSessionConfiguration = {
+ let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
+ configuration.HTTPAdditionalHeaders = Alamofire.Manager.defaultHTTPHeaders
+ configuration.requestCachePolicy = .UseProtocolCachePolicy
+ configuration.URLCache = self.URLCache
+
+ return configuration
+ }()
+
+ let manager = Manager(configuration: configuration)
+
+ return manager
+ }()
+
+ primeCachedResponses()
+ }
+
+ override func tearDown() {
+ super.tearDown()
+
+ self.URLCache.removeAllCachedResponses()
+ }
+
+ // MARK: - Cache Priming Methods
+
+ /**
+ Executes a request for all `Cache-Control` header values to load the response into the `URLCache`.
+
+ This implementation leverages dispatch groups to execute all the requests as well as wait an additional
+ second before returning. This ensures the cache contains responses for all requests that are at least
+ one second old. This allows the tests to distinguish whether the subsequent responses come from the cache
+ or the network based on the timestamp of the response.
+ */
+ func primeCachedResponses() {
+ let dispatchGroup = dispatch_group_create()
+ let highPriorityDispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)
+
+ for cacheControl in CacheControl.allValues {
+ dispatch_group_enter(dispatchGroup)
+
+ let request = self.startRequest(
+ cacheControl: cacheControl,
+ queue: highPriorityDispatchQueue,
+ completion: { _, response in
+ let timestamp = response!.allHeaderFields["Date"] as! String
+ self.timestamps[cacheControl] = timestamp
+
+ dispatch_group_leave(dispatchGroup)
+ }
+ )
+
+ self.requests[cacheControl] = request
+ }
+
+ // Wait for all requests to complete
+ dispatch_group_wait(dispatchGroup, dispatch_time(DISPATCH_TIME_NOW, Int64(10.0 * Float(NSEC_PER_SEC))))
+
+ // Pause for 1 additional second to ensure all timestamps will be different
+ dispatch_group_enter(dispatchGroup)
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(1.0 * Float(NSEC_PER_SEC))), highPriorityDispatchQueue) {
+ dispatch_group_leave(dispatchGroup)
+ }
+
+ // Wait for our 1 second pause to complete
+ dispatch_group_wait(dispatchGroup, dispatch_time(DISPATCH_TIME_NOW, Int64(10.0 * Float(NSEC_PER_SEC))))
+ }
+
+ // MARK: - Request Helper Methods
+
+ func URLRequest(#cacheControl: String, cachePolicy: NSURLRequestCachePolicy) -> NSURLRequest {
+ let parameters = ["Cache-Control": cacheControl]
+ let URL = NSURL(string: self.URLString)!
+ let URLRequest = NSMutableURLRequest(URL: URL, cachePolicy: cachePolicy, timeoutInterval: self.requestTimeout)
+ URLRequest.HTTPMethod = Method.GET.rawValue
+
+ return ParameterEncoding.URL.encode(URLRequest, parameters: parameters).0
+ }
+
+ func startRequest(
+ #cacheControl: String,
+ cachePolicy: NSURLRequestCachePolicy = .UseProtocolCachePolicy,
+ queue: dispatch_queue_t = dispatch_get_main_queue(),
+ completion: (NSURLRequest, NSHTTPURLResponse?) -> Void)
+ -> NSURLRequest
+ {
+ let urlRequest = URLRequest(cacheControl: cacheControl, cachePolicy: cachePolicy)
+
+ let request = self.manager.request(urlRequest)
+ request.response(
+ queue: queue,
+ serializer: Request.responseDataSerializer(),
+ completionHandler: { _, response, _, _ in
+ completion(request.request, response)
+ }
+ )
+
+ return urlRequest
+ }
+
+ // MARK: - Test Execution and Verification
+
+ func executeTest(
+ #cachePolicy: NSURLRequestCachePolicy,
+ cacheControl: String,
+ shouldReturnCachedResponse: Bool)
+ {
+ // Given
+ let expectation = expectationWithDescription("GET request to httpbin")
+ var response: NSHTTPURLResponse?
+
+ // When
+ let request = startRequest(cacheControl: cacheControl, cachePolicy: cachePolicy) { _, responseResponse in
+ response = responseResponse
+ expectation.fulfill()
+ }
+
+ waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
+
+ // Then
+ verifyResponse(response, forCacheControl: cacheControl, isCachedResponse: shouldReturnCachedResponse)
+ }
+
+ func verifyResponse(response: NSHTTPURLResponse?, forCacheControl cacheControl: String, isCachedResponse: Bool) {
+ let cachedResponseTimestamp = self.timestamps[cacheControl]!
+
+ if let
+ response = response,
+ timestamp = response.allHeaderFields["Date"] as? String
+ {
+ if isCachedResponse {
+ XCTAssertEqual(timestamp, cachedResponseTimestamp, "timestamps should be equal")
+ } else {
+ XCTAssertNotEqual(timestamp, cachedResponseTimestamp, "timestamps should not be equal")
+ }
+ } else {
+ XCTFail("response should not be nil")
+ }
+ }
+
+ // MARK: - Tests
+
+ func testURLCacheContainsCachedResponsesForAllRequests() {
+ // Given
+ let publicRequest = self.requests[CacheControl.Public]!
+ let privateRequest = self.requests[CacheControl.Private]!
+ let maxAgeNonExpiredRequest = self.requests[CacheControl.MaxAgeNonExpired]!
+ let maxAgeExpiredRequest = self.requests[CacheControl.MaxAgeExpired]!
+ let noCacheRequest = self.requests[CacheControl.NoCache]!
+ let noStoreRequest = self.requests[CacheControl.NoStore]!
+
+ // When
+ let publicResponse = self.URLCache.cachedResponseForRequest(publicRequest)
+ let privateResponse = self.URLCache.cachedResponseForRequest(privateRequest)
+ let maxAgeNonExpiredResponse = self.URLCache.cachedResponseForRequest(maxAgeNonExpiredRequest)
+ let maxAgeExpiredResponse = self.URLCache.cachedResponseForRequest(maxAgeExpiredRequest)
+ let noCacheResponse = self.URLCache.cachedResponseForRequest(noCacheRequest)
+ let noStoreResponse = self.URLCache.cachedResponseForRequest(noStoreRequest)
+
+ // Then
+ XCTAssertNotNil(publicResponse, "\(CacheControl.Public) response should not be nil")
+ XCTAssertNotNil(privateResponse, "\(CacheControl.Private) response should not be nil")
+ XCTAssertNotNil(maxAgeNonExpiredResponse, "\(CacheControl.MaxAgeNonExpired) response should not be nil")
+ XCTAssertNotNil(maxAgeExpiredResponse, "\(CacheControl.MaxAgeExpired) response should not be nil")
+ XCTAssertNotNil(noCacheResponse, "\(CacheControl.NoCache) response should not be nil")
+
+ #if os(OSX)
+ XCTAssertNil(noStoreResponse, "\(CacheControl.NoStore) response should be nil")
+ #else
+ XCTAssertNotNil(noStoreResponse, "\(CacheControl.NoStore) response should not be nil")
+ #endif
+ }
+
+ func testDefaultCachePolicy() {
+ let cachePolicy: NSURLRequestCachePolicy = .UseProtocolCachePolicy
+
+ executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.Public, shouldReturnCachedResponse: false)
+ executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.Private, shouldReturnCachedResponse: false)
+ executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.MaxAgeNonExpired, shouldReturnCachedResponse: true)
+ executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.MaxAgeExpired, shouldReturnCachedResponse: false)
+ executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.NoCache, shouldReturnCachedResponse: false)
+ executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.NoStore, shouldReturnCachedResponse: false)
+ }
+
+ func testIgnoreLocalCacheDataPolicy() {
+ let cachePolicy: NSURLRequestCachePolicy = .ReloadIgnoringLocalCacheData
+
+ executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.Public, shouldReturnCachedResponse: false)
+ executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.Private, shouldReturnCachedResponse: false)
+ executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.MaxAgeNonExpired, shouldReturnCachedResponse: false)
+ executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.MaxAgeExpired, shouldReturnCachedResponse: false)
+ executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.NoCache, shouldReturnCachedResponse: false)
+ executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.NoStore, shouldReturnCachedResponse: false)
+ }
+
+ func testUseLocalCacheDataIfExistsOtherwiseLoadFromNetworkPolicy() {
+ let cachePolicy: NSURLRequestCachePolicy = .ReturnCacheDataElseLoad
+
+ executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.Public, shouldReturnCachedResponse: true)
+ executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.Private, shouldReturnCachedResponse: true)
+ executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.MaxAgeNonExpired, shouldReturnCachedResponse: true)
+ executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.MaxAgeExpired, shouldReturnCachedResponse: true)
+ executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.NoCache, shouldReturnCachedResponse: true)
+
+ #if os(OSX)
+ executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.NoStore, shouldReturnCachedResponse: false)
+ #else
+ executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.NoStore, shouldReturnCachedResponse: true)
+ #endif
+ }
+
+ func testUseLocalCacheDataAndDontLoadFromNetworkPolicy() {
+ let cachePolicy: NSURLRequestCachePolicy = .ReturnCacheDataDontLoad
+
+ executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.Public, shouldReturnCachedResponse: true)
+ executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.Private, shouldReturnCachedResponse: true)
+ executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.MaxAgeNonExpired, shouldReturnCachedResponse: true)
+ executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.MaxAgeExpired, shouldReturnCachedResponse: true)
+ executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.NoCache, shouldReturnCachedResponse: true)
+
+ #if os(OSX) | Tests/CacheTests.swift | 0 | Swift | 0.214 | question | 53 | 334 | 322 | false | Tests all implemented cache policies against common Cache-Control headers | 505 | Alamofire/Alamofire | 41,690 | Swift | kcharwood | cnoon |
// CacheTests.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Alamofire
import Foundation
import XCTest
/**
This test case tests all implemented cache policies against various `Cache-Control` header values. These tests
are meant to cover the main cases of `Cache-Control` header usage, but are no means exhaustive.
These tests work as follows:
- Set up an `NSURLCache`
- Set up an `Alamofire.Manager`
- Execute requests for all `Cache-Control` headers values to prime the `NSURLCache` with cached responses
- Start up a new test
- Execute another round of the same requests with a given `NSURLRequestCachePolicy`
- Verify whether the response came from the cache or from the network
- This is determined by whether the cached response timestamp matches the new response timestamp
An important thing to note is the difference in behavior between iOS and OS X. On iOS, a response with
a `Cache-Control` header value of `no-store` is still written into the `NSURLCache` where on OS X, it is not.
The different tests below reflect and demonstrate this behavior.
For information about `Cache-Control` HTTP headers, please refer to RFC 2616 - Section 14.9.
*/
class CacheTestCase: BaseTestCase {
// MARK: -
struct CacheControl {
static let Public = "public"
static let Private = "private"
static let MaxAgeNonExpired = "max-age=3600"
static let MaxAgeExpired = "max-age=0"
static let NoCache = "no-cache"
static let NoStore = "no-store"
static var allValues: [String] {
return [
CacheControl.Public,
CacheControl.Private,
CacheControl.MaxAgeNonExpired,
CacheControl.MaxAgeExpired,
CacheControl.NoCache,
CacheControl.NoStore
]
}
}
// MARK: - Properties
var URLCache: NSURLCache!
var manager: Manager!
let URLString = "http://httpbin.org/response-headers"
let requestTimeout: NSTimeInterval = 30
var requests: [String: NSURLRequest] = [:]
var timestamps: [String: String] = [:]
// MARK: - Setup and Teardown
override func setUp() {
super.setUp()
self.URLCache = {
let capacity = 50 * 1024 * 1024 // MBs
let URLCache = NSURLCache(memoryCapacity: capacity, diskCapacity: capacity, diskPath: nil)
return URLCache
}()
self.manager = {
let configuration: NSURLSessionConfiguration = {
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.HTTPAdditionalHeaders = Alamofire.Manager.defaultHTTPHeaders
configuration.requestCachePolicy = .UseProtocolCachePolicy
configuration.URLCache = self.URLCache
return configuration
}()
let manager = Manager(configuration: configuration)
return manager
}()
primeCachedResponses()
}
override func tearDown() {
super.tearDown()
self.URLCache.removeAllCachedResponses()
}
// MARK: - Cache Priming Methods
/**
Executes a request for all `Cache-Control` header values to load the response into the `URLCache`.
This implementation leverages dispatch groups to execute all the requests as well as wait an additional
second before returning. This ensures the cache contains responses for all requests that are at least
one second old. This allows the tests to distinguish whether the subsequent responses come from the cache
or the network based on the timestamp of the response.
*/
func primeCachedResponses() {
let dispatchGroup = dispatch_group_create()
let highPriorityDispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)
for cacheControl in CacheControl.allValues {
dispatch_group_enter(dispatchGroup)
let request = self.startRequest(
cacheControl: cacheControl,
queue: highPriorityDispatchQueue,
completion: { _, response in
let timestamp = response!.allHeaderFields["Date"] as! String
self.timestamps[cacheControl] = timestamp
dispatch_group_leave(dispatchGroup)
}
)
self.requests[cacheControl] = request
}
// Wait for all requests to complete
dispatch_group_wait(dispatchGroup, dispatch_time(DISPATCH_TIME_NOW, Int64(10.0 * Float(NSEC_PER_SEC))))
// Pause for 1 additional second to ensure all timestamps will be different
dispatch_group_enter(dispatchGroup)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(1.0 * Float(NSEC_PER_SEC))), highPriorityDispatchQueue) {
dispatch_group_leave(dispatchGroup)
}
// Wait for our 1 second pause to complete
dispatch_group_wait(dispatchGroup, dispatch_time(DISPATCH_TIME_NOW, Int64(10.0 * Float(NSEC_PER_SEC))))
}
// MARK: - Request Helper Methods
func URLRequest(#cacheControl: String, cachePolicy: NSURLRequestCachePolicy) -> NSURLRequest {
let parameters = ["Cache-Control": cacheControl]
let URL = NSURL(string: self.URLString)!
let URLRequest = NSMutableURLRequest(URL: URL, cachePolicy: cachePolicy, timeoutInterval: self.requestTimeout)
URLRequest.HTTPMethod = Method.GET.rawValue
return ParameterEncoding.URL.encode(URLRequest, parameters: parameters).0
}
func startRequest(
#cacheControl: String,
cachePolicy: NSURLRequestCachePolicy = .UseProtocolCachePolicy,
queue: dispatch_queue_t = dispatch_get_main_queue(),
completion: (NSURLRequest, NSHTTPURLResponse?) -> Void)
-> NSURLRequest
{
let urlRequest = URLRequest(cacheControl: cacheControl, cachePolicy: cachePolicy)
let request = self.manager.request(urlRequest)
request.response(
queue: queue,
serializer: Request.responseDataSerializer(),
completionHandler: { _, response, _, _ in
completion(request.request, response)
}
)
return urlRequest
}
// MARK: - Test Execution and Verification
func executeTest(
#cachePolicy: NSURLRequestCachePolicy,
cacheControl: String,
shouldReturnCachedResponse: Bool)
{
// Given
let expectation = expectationWithDescription("GET request to httpbin")
var response: NSHTTPURLResponse?
// When
let request = startRequest(cacheControl: cacheControl, cachePolicy: cachePolicy) { _, responseResponse in
response = responseResponse
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
verifyResponse(response, forCacheControl: cacheControl, isCachedResponse: shouldReturnCachedResponse)
}
func verifyResponse(response: NSHTTPURLResponse?, forCacheControl cacheControl: String, isCachedResponse: Bool) {
let cachedResponseTimestamp = self.timestamps[cacheControl]!
if let
response = response,
timestamp = response.allHeaderFields["Date"] as? String
{
if isCachedResponse {
XCTAssertEqual(timestamp, cachedResponseTimestamp, "timestamps should be equal")
} else {
XCTAssertNotEqual(timestamp, cachedResponseTimestamp, "timestamps should not be equal")
}
} else {
XCTFail("response should not be nil")
}
}
// MARK: - Tests
func testURLCacheContainsCachedResponsesForAllRequests() {
// Given
let publicRequest = self.requests[CacheControl.Public]!
let privateRequest = self.requests[CacheControl.Private]!
let maxAgeNonExpiredRequest = self.requests[CacheControl.MaxAgeNonExpired]!
let maxAgeExpiredRequest = self.requests[CacheControl.MaxAgeExpired]!
let noCacheRequest = self.requests[CacheControl.NoCache]!
let noStoreRequest = self.requests[CacheControl.NoStore]!
// When
let publicResponse = self.URLCache.cachedResponseForRequest(publicRequest)
let privateResponse = self.URLCache.cachedResponseForRequest(privateRequest)
let maxAgeNonExpiredResponse = self.URLCache.cachedResponseForRequest(maxAgeNonExpiredRequest)
let maxAgeExpiredResponse = self.URLCache.cachedResponseForRequest(maxAgeExpiredRequest)
let noCacheResponse = self.URLCache.cachedResponseForRequest(noCacheRequest)
let noStoreResponse = self.URLCache.cachedResponseForRequest(noStoreRequest)
// Then
XCTAssertNotNil(publicResponse, "\(CacheControl.Public) response should not be nil")
XCTAssertNotNil(privateResponse, "\(CacheControl.Private) response should not be nil")
XCTAssertNotNil(maxAgeNonExpiredResponse, "\(CacheControl.MaxAgeNonExpired) response should not be nil")
XCTAssertNotNil(maxAgeExpiredResponse, "\(CacheControl.MaxAgeExpired) response should not be nil")
XCTAssertNotNil(noCacheResponse, "\(CacheControl.NoCache) response should not be nil")
#if os(OSX)
XCTAssertNil(noStoreResponse, "\(CacheControl.NoStore) response should be nil")
#else
XCTAssertNotNil(noStoreResponse, "\(CacheControl.NoStore) response should not be nil")
#endif
}
func testDefaultCachePolicy() {
let cachePolicy: NSURLRequestCachePolicy = .UseProtocolCachePolicy
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.Public, shouldReturnCachedResponse: false)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.Private, shouldReturnCachedResponse: false)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.MaxAgeNonExpired, shouldReturnCachedResponse: true)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.MaxAgeExpired, shouldReturnCachedResponse: false)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.NoCache, shouldReturnCachedResponse: false)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.NoStore, shouldReturnCachedResponse: false)
}
func testIgnoreLocalCacheDataPolicy() {
let cachePolicy: NSURLRequestCachePolicy = .ReloadIgnoringLocalCacheData
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.Public, shouldReturnCachedResponse: false)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.Private, shouldReturnCachedResponse: false)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.MaxAgeNonExpired, shouldReturnCachedResponse: false)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.MaxAgeExpired, shouldReturnCachedResponse: false)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.NoCache, shouldReturnCachedResponse: false)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.NoStore, shouldReturnCachedResponse: false)
}
func testUseLocalCacheDataIfExistsOtherwiseLoadFromNetworkPolicy() {
let cachePolicy: NSURLRequestCachePolicy = .ReturnCacheDataElseLoad
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.Public, shouldReturnCachedResponse: true)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.Private, shouldReturnCachedResponse: true)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.MaxAgeNonExpired, shouldReturnCachedResponse: true)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.MaxAgeExpired, shouldReturnCachedResponse: true)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.NoCache, shouldReturnCachedResponse: true)
#if os(OSX)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.NoStore, shouldReturnCachedResponse: false)
#else
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.NoStore, shouldReturnCachedResponse: true)
#endif
}
func testUseLocalCacheDataAndDontLoadFromNetworkPolicy() {
let cachePolicy: NSURLRequestCachePolicy = .ReturnCacheDataDontLoad
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.Public, shouldReturnCachedResponse: true)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.Private, shouldReturnCachedResponse: true)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.MaxAgeNonExpired, shouldReturnCachedResponse: true)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.MaxAgeExpired, shouldReturnCachedResponse: true)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.NoCache, shouldReturnCachedResponse: true)
#if os(OSX)
// Given
let expectation = expectationWithDescription("GET request to httpbin")
var response: NSHTTPURLResponse?
// When
let request = startRequest(cacheControl: CacheControl.NoStore, cachePolicy: cachePolicy) { _, responseResponse in
response = responseResponse
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNil(response, "response should be nil")
#else
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.NoStore, shouldReturnCachedResponse: true)
#endif
}
}
| I can now that I've gotten to the bottom of it! 😛
It appears that there was a bug in the iOS 8.2 simulator which I was using when I wrote the tests. Switching over to the iOS 8.3 simulator fixed the issues and we're now seeing the same behavior between iOS and OS X. Thankfully both are producing the "expected" behavior as well at this point since a `Cache-Control` header with a `no-store` value certainly shouldn't cache that request. FWIW, I'm also seeing the wrong behavior in the iOS 8.1 simulator as well.
From what I can tell by scouring the Internets is that people have been reporting all sorts of caching inconsistencies across iOS 8 (including against Alamofire itself). It looks like Apple may have finally gotten iOS 8.3 back in line. I think for now, it's probably best to just move forward. I don't think it makes sense to file a rdar for something they've already fixed. I also don't think it makes a ton of sense to write tests to try to test the older broken behavior. At the moment, we're running Travis against the latest iOS Simulator and OS X x86_64 architecture.
My approach here was to simply get tests around the expected NSURLCache behavior on both platforms, and make sure we stay green here moving forwards. Does that sound reasonable?
| // CacheTests.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Alamofire
import Foundation
import XCTest
/**
This test case tests all implemented cache policies against various `Cache-Control` header values. These tests
are meant to cover the main cases of `Cache-Control` header usage, but are no means exhaustive.
These tests work as follows:
- Set up an `NSURLCache`
- Set up an `Alamofire.Manager`
- Execute requests for all `Cache-Control` headers values to prime the `NSURLCache` with cached responses
- Start up a new test
- Execute another round of the same requests with a given `NSURLRequestCachePolicy`
- Verify whether the response came from the cache or from the network
- This is determined by whether the cached response timestamp matches the new response timestamp
An important thing to note is the difference in behavior between iOS and OS X. On iOS, a response with
a `Cache-Control` header value of `no-store` is still written into the `NSURLCache` where on OS X, it is not.
The different tests below reflect and demonstrate this behavior.
For information about `Cache-Control` HTTP headers, please refer to RFC 2616 - Section 14.9.
*/
class CacheTestCase: BaseTestCase {
// MARK: -
struct CacheControl {
static let Public = "public"
static let Private = "private"
static let MaxAgeNonExpired = "max-age=3600"
static let MaxAgeExpired = "max-age=0"
static let NoCache = "no-cache"
static let NoStore = "no-store"
static var allValues: [String] {
return [
CacheControl.Public,
CacheControl.Private,
CacheControl.MaxAgeNonExpired,
CacheControl.MaxAgeExpired,
CacheControl.NoCache,
CacheControl.NoStore
]
}
}
// MARK: - Properties
var URLCache: NSURLCache!
var manager: Manager!
let URLString = "http://httpbin.org/response-headers"
let requestTimeout: NSTimeInterval = 30
var requests: [String: NSURLRequest] = [:]
var timestamps: [String: String] = [:]
// MARK: - Setup and Teardown
override func setUp() {
super.setUp()
self.URLCache = {
let capacity = 50 * 1024 * 1024 // MBs
let URLCache = NSURLCache(memoryCapacity: capacity, diskCapacity: capacity, diskPath: nil)
return URLCache
}()
self.manager = {
let configuration: NSURLSessionConfiguration = {
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.HTTPAdditionalHeaders = Alamofire.Manager.defaultHTTPHeaders
configuration.requestCachePolicy = .UseProtocolCachePolicy
configuration.URLCache = self.URLCache
return configuration
}()
let manager = Manager(configuration: configuration)
return manager
}()
primeCachedResponses()
}
override func tearDown() {
super.tearDown()
self.URLCache.removeAllCachedResponses()
}
// MARK: - Cache Priming Methods
/**
Executes a request for all `Cache-Control` header values to load the response into the `URLCache`.
This implementation leverages dispatch groups to execute all the requests as well as wait an additional
second before returning. This ensures the cache contains responses for all requests that are at least
one second old. This allows the tests to distinguish whether the subsequent responses come from the cache
or the network based on the timestamp of the response.
*/
func primeCachedResponses() {
let dispatchGroup = dispatch_group_create()
let highPriorityDispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)
for cacheControl in CacheControl.allValues {
dispatch_group_enter(dispatchGroup)
let request = self.startRequest(
cacheControl: cacheControl,
queue: highPriorityDispatchQueue,
completion: { _, response in
let timestamp = response!.allHeaderFields["Date"] as! String
self.timestamps[cacheControl] = timestamp
dispatch_group_leave(dispatchGroup)
}
)
self.requests[cacheControl] = request
}
// Wait for all requests to complete
dispatch_group_wait(dispatchGroup, dispatch_time(DISPATCH_TIME_NOW, Int64(10.0 * Float(NSEC_PER_SEC))))
// Pause for 1 additional second to ensure all timestamps will be different
dispatch_group_enter(dispatchGroup)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(1.0 * Float(NSEC_PER_SEC))), highPriorityDispatchQueue) {
dispatch_group_leave(dispatchGroup)
}
// Wait for our 1 second pause to complete
dispatch_group_wait(dispatchGroup, dispatch_time(DISPATCH_TIME_NOW, Int64(10.0 * Float(NSEC_PER_SEC))))
}
// MARK: - Request Helper Methods
func URLRequest(#cacheControl: String, cachePolicy: NSURLRequestCachePolicy) -> NSURLRequest {
let parameters = ["Cache-Control": cacheControl]
let URL = NSURL(string: self.URLString)!
let URLRequest = NSMutableURLRequest(URL: URL, cachePolicy: cachePolicy, timeoutInterval: self.requestTimeout)
URLRequest.HTTPMethod = Method.GET.rawValue
return ParameterEncoding.URL.encode(URLRequest, parameters: parameters).0
}
func startRequest(
#cacheControl: String,
cachePolicy: NSURLRequestCachePolicy = .UseProtocolCachePolicy,
queue: dispatch_queue_t = dispatch_get_main_queue(),
completion: (NSURLRequest, NSHTTPURLResponse?) -> Void)
-> NSURLRequest
{
let urlRequest = URLRequest(cacheControl: cacheControl, cachePolicy: cachePolicy)
let request = self.manager.request(urlRequest)
request.response(
queue: queue,
serializer: Request.responseDataSerializer(),
completionHandler: { _, response, _, _ in
completion(request.request, response)
}
)
return urlRequest
}
// MARK: - Test Execution and Verification
func executeTest(
#cachePolicy: NSURLRequestCachePolicy,
cacheControl: String,
shouldReturnCachedResponse: Bool)
{
// Given
let expectation = expectationWithDescription("GET request to httpbin")
var response: NSHTTPURLResponse?
// When
let request = startRequest(cacheControl: cacheControl, cachePolicy: cachePolicy) { _, responseResponse in
response = responseResponse
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
verifyResponse(response, forCacheControl: cacheControl, isCachedResponse: shouldReturnCachedResponse)
}
func verifyResponse(response: NSHTTPURLResponse?, forCacheControl cacheControl: String, isCachedResponse: Bool) {
let cachedResponseTimestamp = self.timestamps[cacheControl]!
if let
response = response,
timestamp = response.allHeaderFields["Date"] as? String
{
if isCachedResponse {
XCTAssertEqual(timestamp, cachedResponseTimestamp, "timestamps should be equal")
} else {
XCTAssertNotEqual(timestamp, cachedResponseTimestamp, "timestamps should not be equal")
}
} else {
XCTFail("response should not be nil")
}
}
// MARK: - Tests
func testURLCacheContainsCachedResponsesForAllRequests() {
// Given
let publicRequest = self.requests[CacheControl.Public]!
let privateRequest = self.requests[CacheControl.Private]!
let maxAgeNonExpiredRequest = self.requests[CacheControl.MaxAgeNonExpired]!
let maxAgeExpiredRequest = self.requests[CacheControl.MaxAgeExpired]!
let noCacheRequest = self.requests[CacheControl.NoCache]!
let noStoreRequest = self.requests[CacheControl.NoStore]!
// When
let publicResponse = self.URLCache.cachedResponseForRequest(publicRequest)
let privateResponse = self.URLCache.cachedResponseForRequest(privateRequest)
let maxAgeNonExpiredResponse = self.URLCache.cachedResponseForRequest(maxAgeNonExpiredRequest)
let maxAgeExpiredResponse = self.URLCache.cachedResponseForRequest(maxAgeExpiredRequest)
let noCacheResponse = self.URLCache.cachedResponseForRequest(noCacheRequest)
let noStoreResponse = self.URLCache.cachedResponseForRequest(noStoreRequest)
// Then
XCTAssertNotNil(publicResponse, "\(CacheControl.Public) response should not be nil")
XCTAssertNotNil(privateResponse, "\(CacheControl.Private) response should not be nil")
XCTAssertNotNil(maxAgeNonExpiredResponse, "\(CacheControl.MaxAgeNonExpired) response should not be nil")
XCTAssertNotNil(maxAgeExpiredResponse, "\(CacheControl.MaxAgeExpired) response should not be nil")
XCTAssertNotNil(noCacheResponse, "\(CacheControl.NoCache) response should not be nil")
XCTAssertNil(noStoreResponse, "\(CacheControl.NoStore) response should be nil")
}
func testDefaultCachePolicy() {
let cachePolicy: NSURLRequestCachePolicy = .UseProtocolCachePolicy
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.Public, shouldReturnCachedResponse: false)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.Private, shouldReturnCachedResponse: false)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.MaxAgeNonExpired, shouldReturnCachedResponse: true)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.MaxAgeExpired, shouldReturnCachedResponse: false)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.NoCache, shouldReturnCachedResponse: false)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.NoStore, shouldReturnCachedResponse: false)
}
func testIgnoreLocalCacheDataPolicy() {
let cachePolicy: NSURLRequestCachePolicy = .ReloadIgnoringLocalCacheData
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.Public, shouldReturnCachedResponse: false)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.Private, shouldReturnCachedResponse: false)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.MaxAgeNonExpired, shouldReturnCachedResponse: false)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.MaxAgeExpired, shouldReturnCachedResponse: false)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.NoCache, shouldReturnCachedResponse: false)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.NoStore, shouldReturnCachedResponse: false)
}
func testUseLocalCacheDataIfExistsOtherwiseLoadFromNetworkPolicy() {
let cachePolicy: NSURLRequestCachePolicy = .ReturnCacheDataElseLoad
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.Public, shouldReturnCachedResponse: true)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.Private, shouldReturnCachedResponse: true)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.MaxAgeNonExpired, shouldReturnCachedResponse: true)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.MaxAgeExpired, shouldReturnCachedResponse: true)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.NoCache, shouldReturnCachedResponse: true)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.NoStore, shouldReturnCachedResponse: false)
}
func testUseLocalCacheDataAndDontLoadFromNetworkPolicy() {
let cachePolicy: NSURLRequestCachePolicy = .ReturnCacheDataDontLoad
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.Public, shouldReturnCachedResponse: true)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.Private, shouldReturnCachedResponse: true)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.MaxAgeNonExpired, shouldReturnCachedResponse: true)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.MaxAgeExpired, shouldReturnCachedResponse: true)
executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.NoCache, shouldReturnCachedResponse: true)
// Execute Test - CacheControl.NoStore
// Given
let expectation = expectationWithDescription("GET request to httpbin")
var response: NSHTTPURLResponse?
// When
let request = startRequest(cacheControl: CacheControl.NoStore, cachePolicy: cachePolicy) { _, responseResponse in
response = responseResponse
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNil(response, "response should be nil")
}
}
| @@ -0,0 +1,333 @@
+// CacheTests.swift
+//
+// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+import Alamofire
+import Foundation
+import XCTest
+
+/**
+ This test case tests all implemented cache policies against various `Cache-Control` header values. These tests
+ are meant to cover the main cases of `Cache-Control` header usage, but are no means exhaustive.
+
+ These tests work as follows:
+
+ - Set up an `NSURLCache`
+ - Set up an `Alamofire.Manager`
+ - Execute requests for all `Cache-Control` headers values to prime the `NSURLCache` with cached responses
+ - Start up a new test
+ - Execute another round of the same requests with a given `NSURLRequestCachePolicy`
+ - Verify whether the response came from the cache or from the network
+ - This is determined by whether the cached response timestamp matches the new response timestamp
+
+ An important thing to note is the difference in behavior between iOS and OS X. On iOS, a response with
+ a `Cache-Control` header value of `no-store` is still written into the `NSURLCache` where on OS X, it is not.
+ The different tests below reflect and demonstrate this behavior.
+
+ For information about `Cache-Control` HTTP headers, please refer to RFC 2616 - Section 14.9.
+*/
+class CacheTestCase: BaseTestCase {
+
+ // MARK: -
+
+ struct CacheControl {
+ static let Public = "public"
+ static let Private = "private"
+ static let MaxAgeNonExpired = "max-age=3600"
+ static let MaxAgeExpired = "max-age=0"
+ static let NoCache = "no-cache"
+ static let NoStore = "no-store"
+
+ static var allValues: [String] {
+ return [
+ CacheControl.Public,
+ CacheControl.Private,
+ CacheControl.MaxAgeNonExpired,
+ CacheControl.MaxAgeExpired,
+ CacheControl.NoCache,
+ CacheControl.NoStore
+ ]
+ }
+ }
+
+ // MARK: - Properties
+
+ var URLCache: NSURLCache!
+ var manager: Manager!
+
+ let URLString = "http://httpbin.org/response-headers"
+ let requestTimeout: NSTimeInterval = 30
+
+ var requests: [String: NSURLRequest] = [:]
+ var timestamps: [String: String] = [:]
+
+ // MARK: - Setup and Teardown
+
+ override func setUp() {
+ super.setUp()
+
+ self.URLCache = {
+ let capacity = 50 * 1024 * 1024 // MBs
+ let URLCache = NSURLCache(memoryCapacity: capacity, diskCapacity: capacity, diskPath: nil)
+
+ return URLCache
+ }()
+
+ self.manager = {
+ let configuration: NSURLSessionConfiguration = {
+ let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
+ configuration.HTTPAdditionalHeaders = Alamofire.Manager.defaultHTTPHeaders
+ configuration.requestCachePolicy = .UseProtocolCachePolicy
+ configuration.URLCache = self.URLCache
+
+ return configuration
+ }()
+
+ let manager = Manager(configuration: configuration)
+
+ return manager
+ }()
+
+ primeCachedResponses()
+ }
+
+ override func tearDown() {
+ super.tearDown()
+
+ self.URLCache.removeAllCachedResponses()
+ }
+
+ // MARK: - Cache Priming Methods
+
+ /**
+ Executes a request for all `Cache-Control` header values to load the response into the `URLCache`.
+
+ This implementation leverages dispatch groups to execute all the requests as well as wait an additional
+ second before returning. This ensures the cache contains responses for all requests that are at least
+ one second old. This allows the tests to distinguish whether the subsequent responses come from the cache
+ or the network based on the timestamp of the response.
+ */
+ func primeCachedResponses() {
+ let dispatchGroup = dispatch_group_create()
+ let highPriorityDispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)
+
+ for cacheControl in CacheControl.allValues {
+ dispatch_group_enter(dispatchGroup)
+
+ let request = self.startRequest(
+ cacheControl: cacheControl,
+ queue: highPriorityDispatchQueue,
+ completion: { _, response in
+ let timestamp = response!.allHeaderFields["Date"] as! String
+ self.timestamps[cacheControl] = timestamp
+
+ dispatch_group_leave(dispatchGroup)
+ }
+ )
+
+ self.requests[cacheControl] = request
+ }
+
+ // Wait for all requests to complete
+ dispatch_group_wait(dispatchGroup, dispatch_time(DISPATCH_TIME_NOW, Int64(10.0 * Float(NSEC_PER_SEC))))
+
+ // Pause for 1 additional second to ensure all timestamps will be different
+ dispatch_group_enter(dispatchGroup)
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(1.0 * Float(NSEC_PER_SEC))), highPriorityDispatchQueue) {
+ dispatch_group_leave(dispatchGroup)
+ }
+
+ // Wait for our 1 second pause to complete
+ dispatch_group_wait(dispatchGroup, dispatch_time(DISPATCH_TIME_NOW, Int64(10.0 * Float(NSEC_PER_SEC))))
+ }
+
+ // MARK: - Request Helper Methods
+
+ func URLRequest(#cacheControl: String, cachePolicy: NSURLRequestCachePolicy) -> NSURLRequest {
+ let parameters = ["Cache-Control": cacheControl]
+ let URL = NSURL(string: self.URLString)!
+ let URLRequest = NSMutableURLRequest(URL: URL, cachePolicy: cachePolicy, timeoutInterval: self.requestTimeout)
+ URLRequest.HTTPMethod = Method.GET.rawValue
+
+ return ParameterEncoding.URL.encode(URLRequest, parameters: parameters).0
+ }
+
+ func startRequest(
+ #cacheControl: String,
+ cachePolicy: NSURLRequestCachePolicy = .UseProtocolCachePolicy,
+ queue: dispatch_queue_t = dispatch_get_main_queue(),
+ completion: (NSURLRequest, NSHTTPURLResponse?) -> Void)
+ -> NSURLRequest
+ {
+ let urlRequest = URLRequest(cacheControl: cacheControl, cachePolicy: cachePolicy)
+
+ let request = self.manager.request(urlRequest)
+ request.response(
+ queue: queue,
+ serializer: Request.responseDataSerializer(),
+ completionHandler: { _, response, _, _ in
+ completion(request.request, response)
+ }
+ )
+
+ return urlRequest
+ }
+
+ // MARK: - Test Execution and Verification
+
+ func executeTest(
+ #cachePolicy: NSURLRequestCachePolicy,
+ cacheControl: String,
+ shouldReturnCachedResponse: Bool)
+ {
+ // Given
+ let expectation = expectationWithDescription("GET request to httpbin")
+ var response: NSHTTPURLResponse?
+
+ // When
+ let request = startRequest(cacheControl: cacheControl, cachePolicy: cachePolicy) { _, responseResponse in
+ response = responseResponse
+ expectation.fulfill()
+ }
+
+ waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
+
+ // Then
+ verifyResponse(response, forCacheControl: cacheControl, isCachedResponse: shouldReturnCachedResponse)
+ }
+
+ func verifyResponse(response: NSHTTPURLResponse?, forCacheControl cacheControl: String, isCachedResponse: Bool) {
+ let cachedResponseTimestamp = self.timestamps[cacheControl]!
+
+ if let
+ response = response,
+ timestamp = response.allHeaderFields["Date"] as? String
+ {
+ if isCachedResponse {
+ XCTAssertEqual(timestamp, cachedResponseTimestamp, "timestamps should be equal")
+ } else {
+ XCTAssertNotEqual(timestamp, cachedResponseTimestamp, "timestamps should not be equal")
+ }
+ } else {
+ XCTFail("response should not be nil")
+ }
+ }
+
+ // MARK: - Tests
+
+ func testURLCacheContainsCachedResponsesForAllRequests() {
+ // Given
+ let publicRequest = self.requests[CacheControl.Public]!
+ let privateRequest = self.requests[CacheControl.Private]!
+ let maxAgeNonExpiredRequest = self.requests[CacheControl.MaxAgeNonExpired]!
+ let maxAgeExpiredRequest = self.requests[CacheControl.MaxAgeExpired]!
+ let noCacheRequest = self.requests[CacheControl.NoCache]!
+ let noStoreRequest = self.requests[CacheControl.NoStore]!
+
+ // When
+ let publicResponse = self.URLCache.cachedResponseForRequest(publicRequest)
+ let privateResponse = self.URLCache.cachedResponseForRequest(privateRequest)
+ let maxAgeNonExpiredResponse = self.URLCache.cachedResponseForRequest(maxAgeNonExpiredRequest)
+ let maxAgeExpiredResponse = self.URLCache.cachedResponseForRequest(maxAgeExpiredRequest)
+ let noCacheResponse = self.URLCache.cachedResponseForRequest(noCacheRequest)
+ let noStoreResponse = self.URLCache.cachedResponseForRequest(noStoreRequest)
+
+ // Then
+ XCTAssertNotNil(publicResponse, "\(CacheControl.Public) response should not be nil")
+ XCTAssertNotNil(privateResponse, "\(CacheControl.Private) response should not be nil")
+ XCTAssertNotNil(maxAgeNonExpiredResponse, "\(CacheControl.MaxAgeNonExpired) response should not be nil")
+ XCTAssertNotNil(maxAgeExpiredResponse, "\(CacheControl.MaxAgeExpired) response should not be nil")
+ XCTAssertNotNil(noCacheResponse, "\(CacheControl.NoCache) response should not be nil")
+
+ #if os(OSX)
+ XCTAssertNil(noStoreResponse, "\(CacheControl.NoStore) response should be nil")
+ #else
+ XCTAssertNotNil(noStoreResponse, "\(CacheControl.NoStore) response should not be nil")
+ #endif
+ }
+
+ func testDefaultCachePolicy() {
+ let cachePolicy: NSURLRequestCachePolicy = .UseProtocolCachePolicy
+
+ executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.Public, shouldReturnCachedResponse: false)
+ executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.Private, shouldReturnCachedResponse: false)
+ executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.MaxAgeNonExpired, shouldReturnCachedResponse: true)
+ executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.MaxAgeExpired, shouldReturnCachedResponse: false)
+ executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.NoCache, shouldReturnCachedResponse: false)
+ executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.NoStore, shouldReturnCachedResponse: false)
+ }
+
+ func testIgnoreLocalCacheDataPolicy() {
+ let cachePolicy: NSURLRequestCachePolicy = .ReloadIgnoringLocalCacheData
+
+ executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.Public, shouldReturnCachedResponse: false)
+ executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.Private, shouldReturnCachedResponse: false)
+ executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.MaxAgeNonExpired, shouldReturnCachedResponse: false)
+ executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.MaxAgeExpired, shouldReturnCachedResponse: false)
+ executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.NoCache, shouldReturnCachedResponse: false)
+ executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.NoStore, shouldReturnCachedResponse: false)
+ }
+
+ func testUseLocalCacheDataIfExistsOtherwiseLoadFromNetworkPolicy() {
+ let cachePolicy: NSURLRequestCachePolicy = .ReturnCacheDataElseLoad
+
+ executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.Public, shouldReturnCachedResponse: true)
+ executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.Private, shouldReturnCachedResponse: true)
+ executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.MaxAgeNonExpired, shouldReturnCachedResponse: true)
+ executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.MaxAgeExpired, shouldReturnCachedResponse: true)
+ executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.NoCache, shouldReturnCachedResponse: true)
+
+ #if os(OSX)
+ executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.NoStore, shouldReturnCachedResponse: false)
+ #else
+ executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.NoStore, shouldReturnCachedResponse: true)
+ #endif
+ }
+
+ func testUseLocalCacheDataAndDontLoadFromNetworkPolicy() {
+ let cachePolicy: NSURLRequestCachePolicy = .ReturnCacheDataDontLoad
+
+ executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.Public, shouldReturnCachedResponse: true)
+ executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.Private, shouldReturnCachedResponse: true)
+ executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.MaxAgeNonExpired, shouldReturnCachedResponse: true)
+ executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.MaxAgeExpired, shouldReturnCachedResponse: true)
+ executeTest(cachePolicy: cachePolicy, cacheControl: CacheControl.NoCache, shouldReturnCachedResponse: true)
+
+ #if os(OSX) | Tests/CacheTests.swift | 0 | Swift | 0.786 | bug | 1,268 | 334 | 322 | false | Tests all implemented cache policies against common Cache-Control headers | 505 | Alamofire/Alamofire | 41,690 | Swift | cnoon | cnoon |
// Alamofire.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
extension Manager {
private enum Downloadable {
case Request(NSURLRequest)
case ResumeData(NSData)
}
private func download(downloadable: Downloadable, destination: Request.DownloadFileDestination) -> Request {
var downloadTask: NSURLSessionDownloadTask!
switch downloadable {
case .Request(let request):
dispatch_sync(queue) {
downloadTask = self.session.downloadTaskWithRequest(request)
}
case .ResumeData(let resumeData):
dispatch_sync(queue) {
downloadTask = self.session.downloadTaskWithResumeData(resumeData)
}
}
let request = Request(session: session, task: downloadTask)
if let downloadDelegate = request.delegate as? Request.DownloadTaskDelegate {
downloadDelegate.downloadTaskDidFinishDownloadingToURL = { session, downloadTask, URL in
return destination(URL, downloadTask.response as! NSHTTPURLResponse)
}
}
delegate[request.delegate.task] = request.delegate
if startRequestsImmediately {
request.resume()
}
return request
}
// MARK: Request
/**
Creates a download request using the shared manager instance for the specified method and URL string.
:param: method The HTTP method.
:param: URLString The URL string.
:param: destination The closure used to determine the destination of the downloaded file.
:returns: The created download request.
*/
public func download(method: Method, _ URLString: URLStringConvertible, destination: Request.DownloadFileDestination) -> Request {
return download(URLRequest(method, URLString), destination: destination)
}
/**
Creates a request for downloading from the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
:param: URLRequest The URL request
:param: destination The closure used to determine the destination of the downloaded file.
:returns: The created download request.
*/
public func download(URLRequest: URLRequestConvertible, destination: Request.DownloadFileDestination) -> Request {
return download(.Request(URLRequest.URLRequest), destination: destination)
}
// MARK: Resume Data
/**
Creates a request for downloading from the resume data produced from a previous request cancellation.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
:param: resumeData The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask` when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for additional information.
:param: destination The closure used to determine the destination of the downloaded file.
:returns: The created download request.
*/
public func download(resumeData: NSData, destination: Request.DownloadFileDestination) -> Request {
return download(.ResumeData(resumeData), destination: destination)
}
}
// MARK: -
extension Request {
/**
A closure executed once a request has successfully completed in order to determine where to move the temporary file written to during the download process. The closure takes two arguments: the temporary file URL and the URL response, and returns a single argument: the file URL where the temporary file should be moved.
*/
public typealias DownloadFileDestination = (NSURL, NSHTTPURLResponse) -> NSURL
/**
Creates a download file destination closure which uses the default file manager to move the temporary file to a file URL in the first available directory with the specified search path directory and search path domain mask.
:param: directory The search path directory. `.DocumentDirectory` by default.
:param: domain The search path domain mask. `.UserDomainMask` by default.
:returns: A download file destination closure.
*/
public class func suggestedDownloadDestination(directory: NSSearchPathDirectory = .DocumentDirectory, domain: NSSearchPathDomainMask = .UserDomainMask) -> DownloadFileDestination {
return { temporaryURL, response -> NSURL in
if let directoryURL = NSFileManager.defaultManager().URLsForDirectory(directory, inDomains: domain)[0] as? NSURL {
return directoryURL.URLByAppendingPathComponent(response.suggestedFilename!)
}
return temporaryURL
}
}
// MARK: - DownloadTaskDelegate
class DownloadTaskDelegate: TaskDelegate, NSURLSessionDownloadDelegate {
var downloadTask: NSURLSessionDownloadTask? { return task as? NSURLSessionDownloadTask }
var downloadProgress: ((Int64, Int64, Int64) -> Void)?
var resumeData: NSData?
override var data: NSData? { return resumeData }
// MARK: - NSURLSessionDownloadDelegate
// MARK: Override Closures
var downloadTaskDidFinishDownloadingToURL: ((NSURLSession, NSURLSessionDownloadTask, NSURL) -> NSURL)?
var downloadTaskDidWriteData: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64, Int64) -> Void)?
var downloadTaskDidResumeAtOffset: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64) -> Void)?
// MARK: Delegate Methods
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
if let handler = downloadTaskDidFinishDownloadingToURL {
let destination = handler(session, downloadTask, location)
var fileManagerError: NSError?
NSFileManager.defaultManager().moveItemAtURL(location, toURL: destination, error: &fileManagerError)
if fileManagerError != nil {
error = fileManagerError
}
}
}
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
if let handler = downloadTaskDidWriteData {
handler(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
} else {
progress.totalUnitCount = totalBytesExpectedToWrite
progress.completedUnitCount = totalBytesWritten
downloadProgress?(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
}
}
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
if let handler = downloadTaskDidResumeAtOffset {
handler(session, downloadTask, fileOffset, expectedTotalBytes)
} else {
progress.totalUnitCount = expectedTotalBytes
progress.completedUnitCount = fileOffset
}
}
}
}
| In all the places where you are replacing force unwrapping with optional binding, could you use the following format instead?
``` swift
if let downloadTaskDidFinishDownloadingToURL = self. downloadTaskDidFinishDownloadingToURL {
let destination = downloadTaskDidFinishDownloadingToURL(session, downloadTask, location)
}
```
We have a open task for replacing all property accesses with the `self.` prefix for clarity. This would be a good place to start that work on all these changes.
| // Alamofire.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
extension Manager {
private enum Downloadable {
case Request(NSURLRequest)
case ResumeData(NSData)
}
private func download(downloadable: Downloadable, destination: Request.DownloadFileDestination) -> Request {
var downloadTask: NSURLSessionDownloadTask!
switch downloadable {
case .Request(let request):
dispatch_sync(queue) {
downloadTask = self.session.downloadTaskWithRequest(request)
}
case .ResumeData(let resumeData):
dispatch_sync(queue) {
downloadTask = self.session.downloadTaskWithResumeData(resumeData)
}
}
let request = Request(session: session, task: downloadTask)
if let downloadDelegate = request.delegate as? Request.DownloadTaskDelegate {
downloadDelegate.downloadTaskDidFinishDownloadingToURL = { session, downloadTask, URL in
return destination(URL, downloadTask.response as! NSHTTPURLResponse)
}
}
delegate[request.delegate.task] = request.delegate
if startRequestsImmediately {
request.resume()
}
return request
}
// MARK: Request
/**
Creates a download request using the shared manager instance for the specified method and URL string.
:param: method The HTTP method.
:param: URLString The URL string.
:param: destination The closure used to determine the destination of the downloaded file.
:returns: The created download request.
*/
public func download(method: Method, _ URLString: URLStringConvertible, destination: Request.DownloadFileDestination) -> Request {
return download(URLRequest(method, URLString), destination: destination)
}
/**
Creates a request for downloading from the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
:param: URLRequest The URL request
:param: destination The closure used to determine the destination of the downloaded file.
:returns: The created download request.
*/
public func download(URLRequest: URLRequestConvertible, destination: Request.DownloadFileDestination) -> Request {
return download(.Request(URLRequest.URLRequest), destination: destination)
}
// MARK: Resume Data
/**
Creates a request for downloading from the resume data produced from a previous request cancellation.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
:param: resumeData The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask` when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for additional information.
:param: destination The closure used to determine the destination of the downloaded file.
:returns: The created download request.
*/
public func download(resumeData: NSData, destination: Request.DownloadFileDestination) -> Request {
return download(.ResumeData(resumeData), destination: destination)
}
}
// MARK: -
extension Request {
/**
A closure executed once a request has successfully completed in order to determine where to move the temporary file written to during the download process. The closure takes two arguments: the temporary file URL and the URL response, and returns a single argument: the file URL where the temporary file should be moved.
*/
public typealias DownloadFileDestination = (NSURL, NSHTTPURLResponse) -> NSURL
/**
Creates a download file destination closure which uses the default file manager to move the temporary file to a file URL in the first available directory with the specified search path directory and search path domain mask.
:param: directory The search path directory. `.DocumentDirectory` by default.
:param: domain The search path domain mask. `.UserDomainMask` by default.
:returns: A download file destination closure.
*/
public class func suggestedDownloadDestination(directory: NSSearchPathDirectory = .DocumentDirectory, domain: NSSearchPathDomainMask = .UserDomainMask) -> DownloadFileDestination {
return { temporaryURL, response -> NSURL in
if let directoryURL = NSFileManager.defaultManager().URLsForDirectory(directory, inDomains: domain)[0] as? NSURL {
return directoryURL.URLByAppendingPathComponent(response.suggestedFilename!)
}
return temporaryURL
}
}
// MARK: - DownloadTaskDelegate
class DownloadTaskDelegate: TaskDelegate, NSURLSessionDownloadDelegate {
var downloadTask: NSURLSessionDownloadTask? { return task as? NSURLSessionDownloadTask }
var downloadProgress: ((Int64, Int64, Int64) -> Void)?
var resumeData: NSData?
override var data: NSData? { return resumeData }
// MARK: - NSURLSessionDownloadDelegate
// MARK: Override Closures
var downloadTaskDidFinishDownloadingToURL: ((NSURLSession, NSURLSessionDownloadTask, NSURL) -> NSURL)?
var downloadTaskDidWriteData: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64, Int64) -> Void)?
var downloadTaskDidResumeAtOffset: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64) -> Void)?
// MARK: Delegate Methods
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
if let downloadTaskDidFinishDownloadingToURL = self.downloadTaskDidFinishDownloadingToURL {
let destination = downloadTaskDidFinishDownloadingToURL(session, downloadTask, location)
var fileManagerError: NSError?
NSFileManager.defaultManager().moveItemAtURL(location, toURL: destination, error: &fileManagerError)
if fileManagerError != nil {
error = fileManagerError
}
}
}
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
if let downloadTaskDidWriteData = self.downloadTaskDidWriteData {
downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
} else {
progress.totalUnitCount = totalBytesExpectedToWrite
progress.completedUnitCount = totalBytesWritten
downloadProgress?(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
}
}
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
if let downloadTaskDidResumeAtOffset = self.downloadTaskDidResumeAtOffset {
downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes)
} else {
progress.totalUnitCount = expectedTotalBytes
progress.completedUnitCount = fileOffset
}
}
}
}
| @@ -150,8 +150,8 @@ extension Request {
// MARK: Delegate Methods
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
- if downloadTaskDidFinishDownloadingToURL != nil {
- let destination = downloadTaskDidFinishDownloadingToURL!(session, downloadTask, location)
+ if let handler = downloadTaskDidFinishDownloadingToURL {
+ let destination = handler(session, downloadTask, location) | Source/Download.swift | 0 | Swift | 0.857 | suggestion | 491 | 186 | 186 | false | [Refactoring] Replace many of force unwrapping usages with optional binding and where clause | 557 | Alamofire/Alamofire | 41,690 | Swift | cnoon | ikesyo |
// Alamofire.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
// MARK: - ResponseSerializer
/**
The type in which all response serializers must conform to in order to serialize a response.
*/
public protocol ResponseSerializer {
/// The type of serialized object to be created by this `ResponseSerializer`.
typealias SerializedObject
/// A closure used by response handlers that takes a request, response, and data and returns a serialized object and any error that occured in the process.
var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?) -> (SerializedObject?, NSError?) { get }
}
/**
A generic `ResponseSerializer` used to serialize a request, response, and data into a serialized object.
*/
public struct GenericResponseSerializer<T>: ResponseSerializer {
/// The type of serialized object to be created by this `ResponseSerializer`.
public typealias SerializedObject = T
/// A closure used by response handlers that takes a request, response, and data and returns a serialized object and any error that occured in the process.
public var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?) -> (SerializedObject?, NSError?)
}
// MARK: - Default
extension Request {
/**
Adds a handler to be called once the request has finished.
:param: queue The queue on which the completion handler is dispatched.
:param: responseSerializer The response serializer responsible for serializing the request, response, and data.
:param: completionHandler The code to be executed once the request has finished.
:returns: The request.
*/
public func response<T: ResponseSerializer, V where T.SerializedObject == V>(
queue: dispatch_queue_t? = nil,
responseSerializer: T,
completionHandler: (NSURLRequest, NSHTTPURLResponse?, V?, NSError?) -> Void)
-> Self
{
self.delegate.queue.addOperationWithBlock {
let result: V?
let error: NSError?
(result, error) = responseSerializer.serializeResponse(self.request, self.response, self.delegate.data)
dispatch_async(queue ?? dispatch_get_main_queue()) {
completionHandler(self.request, self.response, result, self.delegate.error ?? error)
}
}
return self
}
}
// MARK: - Data
extension Request {
/**
Creates a response serializer that returns the associated data as-is.
:returns: A data response serializer.
*/
public static func dataResponseSerializer() -> GenericResponseSerializer<NSData> {
return GenericResponseSerializer { request, response, data in
return (data, nil)
}
}
/**
Adds a handler to be called once the request has finished.
:param: completionHandler The code to be executed once the request has finished.
:returns: The request.
*/
public func response(completionHandler: (NSURLRequest, NSHTTPURLResponse?, NSData?, NSError?) -> Void) -> Self {
return response(
responseSerializer: Request.dataResponseSerializer(),
completionHandler: { (request, response, data: NSData?, error) in
completionHandler(request, response, data, error)
}
)
}
}
// MARK: - String
extension Request {
/**
Creates a response serializer that returns a string initialized from the response data with the specified string encoding.
:param: encoding The string encoding. If `nil`, the string encoding will be determined from the server response, falling back to the default HTTP default character set, ISO-8859-1.
:returns: A string response serializer.
*/
public static func stringResponseSerializer(var encoding: NSStringEncoding? = nil) -> GenericResponseSerializer<String> {
return GenericResponseSerializer { _, response, data in
if data == nil || data?.length == 0 {
return (nil, nil)
}
if let encodingName = response?.textEncodingName where encoding == nil {
encoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding(encodingName))
}
let string = NSString(data: data!, encoding: encoding ?? NSISOLatin1StringEncoding) as? String
return (string, nil)
}
}
/**
Adds a handler to be called once the request has finished.
:param: encoding The string encoding. If `nil`, the string encoding will be determined from the server response, falling back to the default HTTP default character set, ISO-8859-1.
:param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the string, if one could be created from the URL response and data, and any error produced while creating the string.
:returns: The request.
*/
public func responseString(
encoding: NSStringEncoding? = nil,
completionHandler: (NSURLRequest, NSHTTPURLResponse?, String?, NSError?) -> Void)
-> Self
{
return response(
responseSerializer: Request.stringResponseSerializer(encoding: encoding),
completionHandler: { (request, response, string: String?, error) in
completionHandler(request, response, string, error)
}
)
}
}
// MARK: - JSON
extension Request {
/**
Creates a response serializer that returns a JSON object constructed from the response data using `NSJSONSerialization` with the specified reading options.
:param: options The JSON serialization reading options. `.AllowFragments` by default.
:returns: A JSON object response serializer.
*/
public static func JSONResponseSerializer(options: NSJSONReadingOptions = .AllowFragments) -> GenericResponseSerializer<AnyObject> {
return GenericResponseSerializer { request, response, data in
if data == nil || data?.length == 0 {
return (nil, nil)
}
var serializationError: NSError?
let JSON: AnyObject? = NSJSONSerialization.JSONObjectWithData(data!, options: options, error: &serializationError)
return (JSON, serializationError)
}
}
/**
Adds a handler to be called once the request has finished.
:param: options The JSON serialization reading options. `.AllowFragments` by default.
:param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the JSON object, if one could be created from the URL response and data, and any error produced while creating the JSON object.
:returns: The request.
*/
public func responseJSON(
options: NSJSONReadingOptions = .AllowFragments,
completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void)
-> Self
{
return response(
responseSerializer: Request.JSONResponseSerializer(options: options),
completionHandler: { (request, response, JSON: AnyObject?, error) in
completionHandler(request, response, JSON, error)
}
)
}
}
// MARK: - Property List
extension Request {
/**
Creates a response serializer that returns an object constructed from the response data using `NSPropertyListSerialization` with the specified reading options.
:param: options The property list reading options. `0` by default.
:returns: A property list object response serializer.
*/
public static func propertyListResponseSerializer(options: NSPropertyListReadOptions = 0) -> GenericResponseSerializer<AnyObject> {
return GenericResponseSerializer { request, response, data in
if data == nil || data?.length == 0 {
return (nil, nil)
}
var propertyListSerializationError: NSError?
let plist: AnyObject? = NSPropertyListSerialization.propertyListWithData(
data!,
options: options,
format: nil,
error: &propertyListSerializationError
)
return (plist, propertyListSerializationError)
}
}
/**
Adds a handler to be called once the request has finished.
:param: options The property list reading options. `0` by default.
:param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the property list, if one could be created from the URL response and data, and any error produced while creating the property list.
:returns: The request.
*/
public func responsePropertyList(
options: NSPropertyListReadOptions = 0,
completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void)
-> Self
{
return response(
responseSerializer: Request.propertyListResponseSerializer(options: options),
completionHandler: { (request, response, plist: AnyObject?, error) in
completionHandler(request, response, plist, error)
}
)
}
}
| I'm curious, why can't you just pass `completionHandler` directly here?
| // Alamofire.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
// MARK: - ResponseSerializer
/**
The type in which all response serializers must conform to in order to serialize a response.
*/
public protocol ResponseSerializer {
/// The type of serialized object to be created by this `ResponseSerializer`.
typealias SerializedObject
/// A closure used by response handlers that takes a request, response, and data and returns a serialized object and any error that occured in the process.
var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?) -> (SerializedObject?, NSError?) { get }
}
/**
A generic `ResponseSerializer` used to serialize a request, response, and data into a serialized object.
*/
public struct GenericResponseSerializer<T>: ResponseSerializer {
/// The type of serialized object to be created by this `ResponseSerializer`.
public typealias SerializedObject = T
/// A closure used by response handlers that takes a request, response, and data and returns a serialized object and any error that occured in the process.
public var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?) -> (SerializedObject?, NSError?)
}
// MARK: - Default
extension Request {
/**
Adds a handler to be called once the request has finished.
:param: queue The queue on which the completion handler is dispatched.
:param: responseSerializer The response serializer responsible for serializing the request, response, and data.
:param: completionHandler The code to be executed once the request has finished.
:returns: The request.
*/
public func response<T: ResponseSerializer, V where T.SerializedObject == V>(
queue: dispatch_queue_t? = nil,
responseSerializer: T,
completionHandler: (NSURLRequest, NSHTTPURLResponse?, V?, NSError?) -> Void)
-> Self
{
self.delegate.queue.addOperationWithBlock {
let result: V?
let error: NSError?
(result, error) = responseSerializer.serializeResponse(self.request, self.response, self.delegate.data)
dispatch_async(queue ?? dispatch_get_main_queue()) {
completionHandler(self.request, self.response, result, self.delegate.error ?? error)
}
}
return self
}
}
// MARK: - Data
extension Request {
/**
Creates a response serializer that returns the associated data as-is.
:returns: A data response serializer.
*/
public static func dataResponseSerializer() -> GenericResponseSerializer<NSData> {
return GenericResponseSerializer { request, response, data in
return (data, nil)
}
}
/**
Adds a handler to be called once the request has finished.
:param: completionHandler The code to be executed once the request has finished.
:returns: The request.
*/
public func response(completionHandler: (NSURLRequest, NSHTTPURLResponse?, NSData?, NSError?) -> Void) -> Self {
return response(responseSerializer: Request.dataResponseSerializer(), completionHandler: completionHandler)
}
}
// MARK: - String
extension Request {
/**
Creates a response serializer that returns a string initialized from the response data with the specified string encoding.
:param: encoding The string encoding. If `nil`, the string encoding will be determined from the server response, falling back to the default HTTP default character set, ISO-8859-1.
:returns: A string response serializer.
*/
public static func stringResponseSerializer(var encoding: NSStringEncoding? = nil) -> GenericResponseSerializer<String> {
return GenericResponseSerializer { _, response, data in
if data == nil || data?.length == 0 {
return (nil, nil)
}
if let encodingName = response?.textEncodingName where encoding == nil {
encoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding(encodingName))
}
let string = NSString(data: data!, encoding: encoding ?? NSISOLatin1StringEncoding) as? String
return (string, nil)
}
}
/**
Adds a handler to be called once the request has finished.
:param: encoding The string encoding. If `nil`, the string encoding will be determined from the server response, falling back to the default HTTP default character set, ISO-8859-1.
:param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the string, if one could be created from the URL response and data, and any error produced while creating the string.
:returns: The request.
*/
public func responseString(
encoding: NSStringEncoding? = nil,
completionHandler: (NSURLRequest, NSHTTPURLResponse?, String?, NSError?) -> Void)
-> Self
{
return response(
responseSerializer: Request.stringResponseSerializer(encoding: encoding),
completionHandler: completionHandler
)
}
}
// MARK: - JSON
extension Request {
/**
Creates a response serializer that returns a JSON object constructed from the response data using `NSJSONSerialization` with the specified reading options.
:param: options The JSON serialization reading options. `.AllowFragments` by default.
:returns: A JSON object response serializer.
*/
public static func JSONResponseSerializer(options: NSJSONReadingOptions = .AllowFragments) -> GenericResponseSerializer<AnyObject> {
return GenericResponseSerializer { request, response, data in
if data == nil || data?.length == 0 {
return (nil, nil)
}
var serializationError: NSError?
let JSON: AnyObject? = NSJSONSerialization.JSONObjectWithData(data!, options: options, error: &serializationError)
return (JSON, serializationError)
}
}
/**
Adds a handler to be called once the request has finished.
:param: options The JSON serialization reading options. `.AllowFragments` by default.
:param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the JSON object, if one could be created from the URL response and data, and any error produced while creating the JSON object.
:returns: The request.
*/
public func responseJSON(
options: NSJSONReadingOptions = .AllowFragments,
completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void)
-> Self
{
return response(
responseSerializer: Request.JSONResponseSerializer(options: options),
completionHandler: completionHandler
)
}
}
// MARK: - Property List
extension Request {
/**
Creates a response serializer that returns an object constructed from the response data using `NSPropertyListSerialization` with the specified reading options.
:param: options The property list reading options. `0` by default.
:returns: A property list object response serializer.
*/
public static func propertyListResponseSerializer(options: NSPropertyListReadOptions = 0) -> GenericResponseSerializer<AnyObject> {
return GenericResponseSerializer { request, response, data in
if data == nil || data?.length == 0 {
return (nil, nil)
}
var propertyListSerializationError: NSError?
let plist: AnyObject? = NSPropertyListSerialization.propertyListWithData(
data!,
options: options,
format: nil,
error: &propertyListSerializationError
)
return (plist, propertyListSerializationError)
}
}
/**
Adds a handler to be called once the request has finished.
:param: options The property list reading options. `0` by default.
:param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the property list, if one could be created from the URL response and data, and any error produced while creating the property list.
:returns: The request.
*/
public func responsePropertyList(
options: NSPropertyListReadOptions = 0,
completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void)
-> Self
{
return response(
responseSerializer: Request.propertyListResponseSerializer(options: options),
completionHandler: completionHandler
)
}
}
| @@ -22,9 +22,100 @@
import Foundation
-// MARK: String
+// MARK: - ResponseSerializer
+
+/**
+ The type in which all response serializers must conform to in order to serialize a response.
+*/
+public protocol ResponseSerializer {
+ /// The type of serialized object to be created by this `ResponseSerializer`.
+ typealias SerializedObject
+
+ /// A closure used by response handlers that takes a request, response, and data and returns a serialized object and any error that occured in the process.
+ var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?) -> (SerializedObject?, NSError?) { get }
+}
+
+/**
+ A generic `ResponseSerializer` used to serialize a request, response, and data into a serialized object.
+*/
+public struct GenericResponseSerializer<T>: ResponseSerializer {
+ /// The type of serialized object to be created by this `ResponseSerializer`.
+ public typealias SerializedObject = T
+
+ /// A closure used by response handlers that takes a request, response, and data and returns a serialized object and any error that occured in the process.
+ public var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?) -> (SerializedObject?, NSError?)
+}
+
+// MARK: - Default
+
+extension Request {
+
+ /**
+ Adds a handler to be called once the request has finished.
+
+ :param: queue The queue on which the completion handler is dispatched.
+ :param: responseSerializer The response serializer responsible for serializing the request, response, and data.
+ :param: completionHandler The code to be executed once the request has finished.
+
+ :returns: The request.
+ */
+ public func response<T: ResponseSerializer, V where T.SerializedObject == V>(
+ queue: dispatch_queue_t? = nil,
+ responseSerializer: T,
+ completionHandler: (NSURLRequest, NSHTTPURLResponse?, V?, NSError?) -> Void)
+ -> Self
+ {
+ self.delegate.queue.addOperationWithBlock {
+ let result: V?
+ let error: NSError?
+
+ (result, error) = responseSerializer.serializeResponse(self.request, self.response, self.delegate.data)
+
+ dispatch_async(queue ?? dispatch_get_main_queue()) {
+ completionHandler(self.request, self.response, result, self.delegate.error ?? error)
+ }
+ }
+
+ return self
+ }
+}
+
+// MARK: - Data
+
+extension Request {
+
+ /**
+ Creates a response serializer that returns the associated data as-is.
+
+ :returns: A data response serializer.
+ */
+ public static func dataResponseSerializer() -> GenericResponseSerializer<NSData> {
+ return GenericResponseSerializer { request, response, data in
+ return (data, nil)
+ }
+ }
+
+ /**
+ Adds a handler to be called once the request has finished.
+
+ :param: completionHandler The code to be executed once the request has finished.
+
+ :returns: The request.
+ */
+ public func response(completionHandler: (NSURLRequest, NSHTTPURLResponse?, NSData?, NSError?) -> Void) -> Self {
+ return response(
+ responseSerializer: Request.dataResponseSerializer(),
+ completionHandler: { (request, response, data: NSData?, error) in | Source/ResponseSerialization.swift | 0 | Swift | 0.5 | question | 73 | 260 | 249 | false | Feature - Response Serializer Generics | 593 | Alamofire/Alamofire | 41,690 | Swift | jqsilver | cnoon |
}
/**
Adds a handler to be called once the request has finished.
:param: completionHandler The code to be executed once the request has finished.
:returns: The request.
*/
public func response(completionHandler: (NSURLRequest, NSHTTPURLResponse?, NSData?, NSError?) -> Void) -> Self {
return response(
responseSerializer: Request.dataResponseSerializer(),
completionHandler: { (request, response, data: NSData?, error) in
completionHandler(request, response, data, error)
}
)
}
}
// MARK: - String
extension Request {
/**
Creates a response serializer that returns a string initialized from the response data with the specified string encoding.
:param: encoding The string encoding. If `nil`, the string encoding will be determined from the server response, falling back to the default HTTP default character set, ISO-8859-1.
:returns: A string response serializer.
*/
public static func stringResponseSerializer(var encoding: NSStringEncoding? = nil) -> GenericResponseSerializer<String> {
return GenericResponseSerializer { _, response, data in
if data == nil || data?.length == 0 {
return (nil, nil)
}
if let encodingName = response?.textEncodingName where encoding == nil {
encoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding(encodingName))
}
let string = NSString(data: data!, encoding: encoding ?? NSISOLatin1StringEncoding) as? String
return (string, nil)
}
}
/**
Adds a handler to be called once the request has finished.
:param: encoding The string encoding. If `nil`, the string encoding will be determined from the server response, falling back to the default HTTP default character set, ISO-8859-1.
:param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the string, if one could be created from the URL response and data, and any error produced while creating the string. | Why cant it be a class method?
| }
/**
Adds a handler to be called once the request has finished.
:param: completionHandler The code to be executed once the request has finished.
:returns: The request.
*/
public func response(completionHandler: (NSURLRequest, NSHTTPURLResponse?, NSData?, NSError?) -> Void) -> Self {
return response(responseSerializer: Request.dataResponseSerializer(), completionHandler: completionHandler)
}
}
// MARK: - String
extension Request {
/**
Creates a response serializer that returns a string initialized from the response data with the specified string encoding.
:param: encoding The string encoding. If `nil`, the string encoding will be determined from the server response, falling back to the default HTTP default character set, ISO-8859-1.
:returns: A string response serializer.
*/
public static func stringResponseSerializer(var encoding: NSStringEncoding? = nil) -> GenericResponseSerializer<String> {
return GenericResponseSerializer { _, response, data in
if data == nil || data?.length == 0 {
return (nil, nil)
}
if let encodingName = response?.textEncodingName where encoding == nil {
encoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding(encodingName))
}
let string = NSString(data: data!, encoding: encoding ?? NSISOLatin1StringEncoding) as? String
return (string, nil)
}
}
/**
Adds a handler to be called once the request has finished.
:param: encoding The string encoding. If `nil`, the string encoding will be determined from the server response, falling back to the default HTTP default character set, ISO-8859-1.
:param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the string, if one could be created from the URL response and data, and any error produced while creating the string.
:returns: The request.
*/
public func responseString(
encoding: NSStringEncoding? = nil, | @@ -32,8 +123,8 @@ extension Request {
:returns: A string response serializer.
*/
- public class func stringResponseSerializer(var encoding: NSStringEncoding? = nil) -> Serializer {
- return { _, response, data in
+ public static func stringResponseSerializer(var encoding: NSStringEncoding? = nil) -> GenericResponseSerializer<String> { | Source/ResponseSerialization.swift | 26 | Swift | 0.071 | question | 31 | 51 | 51 | false | Feature - Response Serializer Generics | 593 | Alamofire/Alamofire | 41,690 | Swift | NicholasTD07 | cnoon |
// Alamofire.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
// MARK: - ResponseSerializer
/**
The type in which all response serializers must conform to in order to serialize a response.
*/
public protocol ResponseSerializer {
/// The type of serialized object to be created by this `ResponseSerializer`.
typealias SerializedObject
/// A closure used by response handlers that takes a request, response, and data and returns a serialized object and any error that occured in the process.
var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?) -> (SerializedObject?, NSError?) { get }
}
/**
A generic `ResponseSerializer` used to serialize a request, response, and data into a serialized object.
*/
public struct GenericResponseSerializer<T>: ResponseSerializer {
/// The type of serialized object to be created by this `ResponseSerializer`.
public typealias SerializedObject = T
/// A closure used by response handlers that takes a request, response, and data and returns a serialized object and any error that occured in the process.
public var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?) -> (SerializedObject?, NSError?)
}
// MARK: - Default
extension Request {
/**
Adds a handler to be called once the request has finished.
:param: queue The queue on which the completion handler is dispatched.
:param: responseSerializer The response serializer responsible for serializing the request, response, and data.
:param: completionHandler The code to be executed once the request has finished.
:returns: The request.
*/
public func response<T: ResponseSerializer, V where T.SerializedObject == V>(
queue: dispatch_queue_t? = nil,
responseSerializer: T,
completionHandler: (NSURLRequest, NSHTTPURLResponse?, V?, NSError?) -> Void)
-> Self
{
self.delegate.queue.addOperationWithBlock {
let result: V?
let error: NSError?
(result, error) = responseSerializer.serializeResponse(self.request, self.response, self.delegate.data)
dispatch_async(queue ?? dispatch_get_main_queue()) {
completionHandler(self.request, self.response, result, self.delegate.error ?? error)
}
}
return self
}
}
// MARK: - Data
extension Request {
/**
Creates a response serializer that returns the associated data as-is.
:returns: A data response serializer.
*/
public static func dataResponseSerializer() -> GenericResponseSerializer<NSData> {
return GenericResponseSerializer { request, response, data in
return (data, nil)
}
}
/**
Adds a handler to be called once the request has finished.
:param: completionHandler The code to be executed once the request has finished.
:returns: The request.
*/
public func response(completionHandler: (NSURLRequest, NSHTTPURLResponse?, NSData?, NSError?) -> Void) -> Self {
return response(
responseSerializer: Request.dataResponseSerializer(),
completionHandler: { (request, response, data: NSData?, error) in
completionHandler(request, response, data, error)
}
)
}
}
// MARK: - String
extension Request {
/**
Creates a response serializer that returns a string initialized from the response data with the specified string encoding.
:param: encoding The string encoding. If `nil`, the string encoding will be determined from the server response, falling back to the default HTTP default character set, ISO-8859-1.
:returns: A string response serializer.
*/
public static func stringResponseSerializer(var encoding: NSStringEncoding? = nil) -> GenericResponseSerializer<String> {
return GenericResponseSerializer { _, response, data in
if data == nil || data?.length == 0 {
return (nil, nil)
}
if let encodingName = response?.textEncodingName where encoding == nil {
encoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding(encodingName))
}
let string = NSString(data: data!, encoding: encoding ?? NSISOLatin1StringEncoding) as? String
return (string, nil)
}
}
/**
Adds a handler to be called once the request has finished.
:param: encoding The string encoding. If `nil`, the string encoding will be determined from the server response, falling back to the default HTTP default character set, ISO-8859-1.
:param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the string, if one could be created from the URL response and data, and any error produced while creating the string.
:returns: The request.
*/
public func responseString(
encoding: NSStringEncoding? = nil,
completionHandler: (NSURLRequest, NSHTTPURLResponse?, String?, NSError?) -> Void)
-> Self
{
return response(
responseSerializer: Request.stringResponseSerializer(encoding: encoding),
completionHandler: { (request, response, string: String?, error) in
completionHandler(request, response, string, error)
}
)
}
}
// MARK: - JSON
extension Request {
/**
Creates a response serializer that returns a JSON object constructed from the response data using `NSJSONSerialization` with the specified reading options.
:param: options The JSON serialization reading options. `.AllowFragments` by default.
:returns: A JSON object response serializer.
*/
public static func JSONResponseSerializer(options: NSJSONReadingOptions = .AllowFragments) -> GenericResponseSerializer<AnyObject> {
return GenericResponseSerializer { request, response, data in
if data == nil || data?.length == 0 {
return (nil, nil)
}
var serializationError: NSError?
let JSON: AnyObject? = NSJSONSerialization.JSONObjectWithData(data!, options: options, error: &serializationError)
return (JSON, serializationError)
}
}
/**
Adds a handler to be called once the request has finished.
:param: options The JSON serialization reading options. `.AllowFragments` by default.
:param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the JSON object, if one could be created from the URL response and data, and any error produced while creating the JSON object.
:returns: The request.
*/
public func responseJSON(
options: NSJSONReadingOptions = .AllowFragments,
completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void)
-> Self
{
return response(
responseSerializer: Request.JSONResponseSerializer(options: options),
completionHandler: { (request, response, JSON: AnyObject?, error) in
completionHandler(request, response, JSON, error)
}
)
}
}
// MARK: - Property List
extension Request {
/**
Creates a response serializer that returns an object constructed from the response data using `NSPropertyListSerialization` with the specified reading options.
:param: options The property list reading options. `0` by default.
:returns: A property list object response serializer.
*/
public static func propertyListResponseSerializer(options: NSPropertyListReadOptions = 0) -> GenericResponseSerializer<AnyObject> {
return GenericResponseSerializer { request, response, data in
if data == nil || data?.length == 0 {
return (nil, nil)
}
var propertyListSerializationError: NSError?
let plist: AnyObject? = NSPropertyListSerialization.propertyListWithData(
data!,
options: options,
format: nil,
error: &propertyListSerializationError
)
return (plist, propertyListSerializationError)
}
}
/**
Adds a handler to be called once the request has finished.
:param: options The property list reading options. `0` by default.
:param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the property list, if one could be created from the URL response and data, and any error produced while creating the property list.
:returns: The request.
*/
public func responsePropertyList(
options: NSPropertyListReadOptions = 0,
completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void)
-> Self
{
return response(
responseSerializer: Request.propertyListResponseSerializer(options: options),
completionHandler: { (request, response, plist: AnyObject?, error) in
completionHandler(request, response, plist, error)
}
)
}
}
| Great catch guys! It was previously necessary and I didn't catch that it could be removed. Addressed in ed752d39.
| // Alamofire.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
// MARK: - ResponseSerializer
/**
The type in which all response serializers must conform to in order to serialize a response.
*/
public protocol ResponseSerializer {
/// The type of serialized object to be created by this `ResponseSerializer`.
typealias SerializedObject
/// A closure used by response handlers that takes a request, response, and data and returns a serialized object and any error that occured in the process.
var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?) -> (SerializedObject?, NSError?) { get }
}
/**
A generic `ResponseSerializer` used to serialize a request, response, and data into a serialized object.
*/
public struct GenericResponseSerializer<T>: ResponseSerializer {
/// The type of serialized object to be created by this `ResponseSerializer`.
public typealias SerializedObject = T
/// A closure used by response handlers that takes a request, response, and data and returns a serialized object and any error that occured in the process.
public var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?) -> (SerializedObject?, NSError?)
}
// MARK: - Default
extension Request {
/**
Adds a handler to be called once the request has finished.
:param: queue The queue on which the completion handler is dispatched.
:param: responseSerializer The response serializer responsible for serializing the request, response, and data.
:param: completionHandler The code to be executed once the request has finished.
:returns: The request.
*/
public func response<T: ResponseSerializer, V where T.SerializedObject == V>(
queue: dispatch_queue_t? = nil,
responseSerializer: T,
completionHandler: (NSURLRequest, NSHTTPURLResponse?, V?, NSError?) -> Void)
-> Self
{
self.delegate.queue.addOperationWithBlock {
let result: V?
let error: NSError?
(result, error) = responseSerializer.serializeResponse(self.request, self.response, self.delegate.data)
dispatch_async(queue ?? dispatch_get_main_queue()) {
completionHandler(self.request, self.response, result, self.delegate.error ?? error)
}
}
return self
}
}
// MARK: - Data
extension Request {
/**
Creates a response serializer that returns the associated data as-is.
:returns: A data response serializer.
*/
public static func dataResponseSerializer() -> GenericResponseSerializer<NSData> {
return GenericResponseSerializer { request, response, data in
return (data, nil)
}
}
/**
Adds a handler to be called once the request has finished.
:param: completionHandler The code to be executed once the request has finished.
:returns: The request.
*/
public func response(completionHandler: (NSURLRequest, NSHTTPURLResponse?, NSData?, NSError?) -> Void) -> Self {
return response(responseSerializer: Request.dataResponseSerializer(), completionHandler: completionHandler)
}
}
// MARK: - String
extension Request {
/**
Creates a response serializer that returns a string initialized from the response data with the specified string encoding.
:param: encoding The string encoding. If `nil`, the string encoding will be determined from the server response, falling back to the default HTTP default character set, ISO-8859-1.
:returns: A string response serializer.
*/
public static func stringResponseSerializer(var encoding: NSStringEncoding? = nil) -> GenericResponseSerializer<String> {
return GenericResponseSerializer { _, response, data in
if data == nil || data?.length == 0 {
return (nil, nil)
}
if let encodingName = response?.textEncodingName where encoding == nil {
encoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding(encodingName))
}
let string = NSString(data: data!, encoding: encoding ?? NSISOLatin1StringEncoding) as? String
return (string, nil)
}
}
/**
Adds a handler to be called once the request has finished.
:param: encoding The string encoding. If `nil`, the string encoding will be determined from the server response, falling back to the default HTTP default character set, ISO-8859-1.
:param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the string, if one could be created from the URL response and data, and any error produced while creating the string.
:returns: The request.
*/
public func responseString(
encoding: NSStringEncoding? = nil,
completionHandler: (NSURLRequest, NSHTTPURLResponse?, String?, NSError?) -> Void)
-> Self
{
return response(
responseSerializer: Request.stringResponseSerializer(encoding: encoding),
completionHandler: completionHandler
)
}
}
// MARK: - JSON
extension Request {
/**
Creates a response serializer that returns a JSON object constructed from the response data using `NSJSONSerialization` with the specified reading options.
:param: options The JSON serialization reading options. `.AllowFragments` by default.
:returns: A JSON object response serializer.
*/
public static func JSONResponseSerializer(options: NSJSONReadingOptions = .AllowFragments) -> GenericResponseSerializer<AnyObject> {
return GenericResponseSerializer { request, response, data in
if data == nil || data?.length == 0 {
return (nil, nil)
}
var serializationError: NSError?
let JSON: AnyObject? = NSJSONSerialization.JSONObjectWithData(data!, options: options, error: &serializationError)
return (JSON, serializationError)
}
}
/**
Adds a handler to be called once the request has finished.
:param: options The JSON serialization reading options. `.AllowFragments` by default.
:param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the JSON object, if one could be created from the URL response and data, and any error produced while creating the JSON object.
:returns: The request.
*/
public func responseJSON(
options: NSJSONReadingOptions = .AllowFragments,
completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void)
-> Self
{
return response(
responseSerializer: Request.JSONResponseSerializer(options: options),
completionHandler: completionHandler
)
}
}
// MARK: - Property List
extension Request {
/**
Creates a response serializer that returns an object constructed from the response data using `NSPropertyListSerialization` with the specified reading options.
:param: options The property list reading options. `0` by default.
:returns: A property list object response serializer.
*/
public static func propertyListResponseSerializer(options: NSPropertyListReadOptions = 0) -> GenericResponseSerializer<AnyObject> {
return GenericResponseSerializer { request, response, data in
if data == nil || data?.length == 0 {
return (nil, nil)
}
var propertyListSerializationError: NSError?
let plist: AnyObject? = NSPropertyListSerialization.propertyListWithData(
data!,
options: options,
format: nil,
error: &propertyListSerializationError
)
return (plist, propertyListSerializationError)
}
}
/**
Adds a handler to be called once the request has finished.
:param: options The property list reading options. `0` by default.
:param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the property list, if one could be created from the URL response and data, and any error produced while creating the property list.
:returns: The request.
*/
public func responsePropertyList(
options: NSPropertyListReadOptions = 0,
completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void)
-> Self
{
return response(
responseSerializer: Request.propertyListResponseSerializer(options: options),
completionHandler: completionHandler
)
}
}
| @@ -22,9 +22,100 @@
import Foundation
-// MARK: String
+// MARK: - ResponseSerializer
+
+/**
+ The type in which all response serializers must conform to in order to serialize a response.
+*/
+public protocol ResponseSerializer {
+ /// The type of serialized object to be created by this `ResponseSerializer`.
+ typealias SerializedObject
+
+ /// A closure used by response handlers that takes a request, response, and data and returns a serialized object and any error that occured in the process.
+ var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?) -> (SerializedObject?, NSError?) { get }
+}
+
+/**
+ A generic `ResponseSerializer` used to serialize a request, response, and data into a serialized object.
+*/
+public struct GenericResponseSerializer<T>: ResponseSerializer {
+ /// The type of serialized object to be created by this `ResponseSerializer`.
+ public typealias SerializedObject = T
+
+ /// A closure used by response handlers that takes a request, response, and data and returns a serialized object and any error that occured in the process.
+ public var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?) -> (SerializedObject?, NSError?)
+}
+
+// MARK: - Default
+
+extension Request {
+
+ /**
+ Adds a handler to be called once the request has finished.
+
+ :param: queue The queue on which the completion handler is dispatched.
+ :param: responseSerializer The response serializer responsible for serializing the request, response, and data.
+ :param: completionHandler The code to be executed once the request has finished.
+
+ :returns: The request.
+ */
+ public func response<T: ResponseSerializer, V where T.SerializedObject == V>(
+ queue: dispatch_queue_t? = nil,
+ responseSerializer: T,
+ completionHandler: (NSURLRequest, NSHTTPURLResponse?, V?, NSError?) -> Void)
+ -> Self
+ {
+ self.delegate.queue.addOperationWithBlock {
+ let result: V?
+ let error: NSError?
+
+ (result, error) = responseSerializer.serializeResponse(self.request, self.response, self.delegate.data)
+
+ dispatch_async(queue ?? dispatch_get_main_queue()) {
+ completionHandler(self.request, self.response, result, self.delegate.error ?? error)
+ }
+ }
+
+ return self
+ }
+}
+
+// MARK: - Data
+
+extension Request {
+
+ /**
+ Creates a response serializer that returns the associated data as-is.
+
+ :returns: A data response serializer.
+ */
+ public static func dataResponseSerializer() -> GenericResponseSerializer<NSData> {
+ return GenericResponseSerializer { request, response, data in
+ return (data, nil)
+ }
+ }
+
+ /**
+ Adds a handler to be called once the request has finished.
+
+ :param: completionHandler The code to be executed once the request has finished.
+
+ :returns: The request.
+ */
+ public func response(completionHandler: (NSURLRequest, NSHTTPURLResponse?, NSData?, NSError?) -> Void) -> Self {
+ return response(
+ responseSerializer: Request.dataResponseSerializer(),
+ completionHandler: { (request, response, data: NSData?, error) in | Source/ResponseSerialization.swift | 0 | Swift | 0.429 | suggestion | 114 | 260 | 249 | false | Feature - Response Serializer Generics | 593 | Alamofire/Alamofire | 41,690 | Swift | cnoon | cnoon |
}
/**
Adds a handler to be called once the request has finished.
:param: completionHandler The code to be executed once the request has finished.
:returns: The request.
*/
public func response(completionHandler: (NSURLRequest, NSHTTPURLResponse?, NSData?, NSError?) -> Void) -> Self {
return response(
responseSerializer: Request.dataResponseSerializer(),
completionHandler: { (request, response, data: NSData?, error) in
completionHandler(request, response, data, error)
}
)
}
}
// MARK: - String
extension Request {
/**
Creates a response serializer that returns a string initialized from the response data with the specified string encoding.
:param: encoding The string encoding. If `nil`, the string encoding will be determined from the server response, falling back to the default HTTP default character set, ISO-8859-1.
:returns: A string response serializer.
*/
public static func stringResponseSerializer(var encoding: NSStringEncoding? = nil) -> GenericResponseSerializer<String> {
return GenericResponseSerializer { _, response, data in
if data == nil || data?.length == 0 {
return (nil, nil)
}
if let encodingName = response?.textEncodingName where encoding == nil {
encoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding(encodingName))
}
let string = NSString(data: data!, encoding: encoding ?? NSISOLatin1StringEncoding) as? String
return (string, nil)
}
}
/**
Adds a handler to be called once the request has finished.
:param: encoding The string encoding. If `nil`, the string encoding will be determined from the server response, falling back to the default HTTP default character set, ISO-8859-1.
:param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the string, if one could be created from the URL response and data, and any error produced while creating the string. | So it certainly could be, but my thought was that it shouldn't be. Here are a couple questions that I think will help us find the right balance:
- Does it really make sense to subclass the `data`, `string`, `JSON` or `propertyList` response serializers?
- Does it even make sense to subclass `Request` at all?
> IMO the answer to both is NO.
The recommended usage here is certainly to extend `Request` to provide your own custom response serializations. You would implement your own `responseSomeCustomName` method that could either call one of the four default response serializers, or you would also create a `CustomResponseSerializer<T>` to handle your use case.
Even in the event that you did end up subclassing `Request`, would it make sense to really override any of the four default response serializers with custom behavior? Wouldn't you instead implement your own generic response serializer and call your own custom response method? This was my reasoning for going with `static` rather than `class`.
Thoughts?
| }
/**
Adds a handler to be called once the request has finished.
:param: completionHandler The code to be executed once the request has finished.
:returns: The request.
*/
public func response(completionHandler: (NSURLRequest, NSHTTPURLResponse?, NSData?, NSError?) -> Void) -> Self {
return response(responseSerializer: Request.dataResponseSerializer(), completionHandler: completionHandler)
}
}
// MARK: - String
extension Request {
/**
Creates a response serializer that returns a string initialized from the response data with the specified string encoding.
:param: encoding The string encoding. If `nil`, the string encoding will be determined from the server response, falling back to the default HTTP default character set, ISO-8859-1.
:returns: A string response serializer.
*/
public static func stringResponseSerializer(var encoding: NSStringEncoding? = nil) -> GenericResponseSerializer<String> {
return GenericResponseSerializer { _, response, data in
if data == nil || data?.length == 0 {
return (nil, nil)
}
if let encodingName = response?.textEncodingName where encoding == nil {
encoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding(encodingName))
}
let string = NSString(data: data!, encoding: encoding ?? NSISOLatin1StringEncoding) as? String
return (string, nil)
}
}
/**
Adds a handler to be called once the request has finished.
:param: encoding The string encoding. If `nil`, the string encoding will be determined from the server response, falling back to the default HTTP default character set, ISO-8859-1.
:param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the string, if one could be created from the URL response and data, and any error produced while creating the string.
:returns: The request.
*/
public func responseString(
encoding: NSStringEncoding? = nil, | @@ -32,8 +123,8 @@ extension Request {
:returns: A string response serializer.
*/
- public class func stringResponseSerializer(var encoding: NSStringEncoding? = nil) -> Serializer {
- return { _, response, data in
+ public static func stringResponseSerializer(var encoding: NSStringEncoding? = nil) -> GenericResponseSerializer<String> { | Source/ResponseSerialization.swift | 26 | Swift | 0.786 | question | 1,026 | 51 | 51 | false | Feature - Response Serializer Generics | 593 | Alamofire/Alamofire | 41,690 | Swift | cnoon | cnoon |
let expectation = expectationWithDescription("Download should be cancelled")
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var data: AnyObject?
var error: NSError?
// When
let download = Alamofire.download(.GET, self.URLString, destination: self.destination)
.response { responseRequest, responseResponse, responseData, responseError in
request = responseRequest
response = responseResponse
data = responseData
error = responseError
expectation.fulfill()
}
download.cancel()
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNil(response, "response should be nil")
XCTAssertNil(data, "data should be nil")
XCTAssertNotNil(error, "error should not be nil")
}
func testThatCancelledDownloadResponseDataMatchesResumeData() {
// Given
let expectation = expectationWithDescription("Download should be cancelled")
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var data: AnyObject?
var error: NSError?
// When
let download = Alamofire.download(.GET, self.URLString, destination: self.destination)
download.progress { _, _, _ in
download.cancel()
}
download.response { responseRequest, responseResponse, responseData, responseError in
request = responseRequest
response = responseResponse
data = responseData
error = responseError
expectation.fulfill()
} | Should this not also assert that resumeData is nil?
| let expectation = expectationWithDescription("Download should be cancelled")
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var data: AnyObject?
var error: NSError?
// When
let download = Alamofire.download(.GET, self.URLString, destination: self.destination)
.response { responseRequest, responseResponse, responseData, responseError in
request = responseRequest
response = responseResponse
data = responseData
error = responseError
expectation.fulfill()
}
download.cancel()
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNil(response, "response should be nil")
XCTAssertNil(data, "data should be nil")
XCTAssertNotNil(error, "error should not be nil")
XCTAssertNil(download.resumeData, "resume data should be nil")
}
func testThatCancelledDownloadResponseDataMatchesResumeData() {
// Given
let expectation = expectationWithDescription("Download should be cancelled")
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var data: AnyObject?
var error: NSError?
// When
let download = Alamofire.download(.GET, self.URLString, destination: self.destination)
download.progress { _, _, _ in
download.cancel()
}
download.response { responseRequest, responseResponse, responseData, responseError in
request = responseRequest
response = responseResponse
data = responseData
error = responseError
| @@ -216,3 +212,123 @@ class DownloadResponseTestCase: BaseTestCase {
XCTAssertNil(removalError, "removal error should be nil")
}
}
+
+// MARK: -
+
+class DownloadResumeDataTestCase: BaseTestCase {
+ let URLString = "https://upload.wikimedia.org/wikipedia/commons/6/69/NASA-HS201427a-HubbleUltraDeepField2014-20140603.jpg"
+ let destination: Request.DownloadFileDestination = {
+ let searchPathDirectory: NSSearchPathDirectory = .CachesDirectory
+ let searchPathDomain: NSSearchPathDomainMask = .UserDomainMask
+
+ return Request.suggestedDownloadDestination(directory: searchPathDirectory, domain: searchPathDomain)
+ }()
+
+ func testThatImmediatelyCancelledDownloadDoesNotHaveResumeDataAvailable() {
+ // Given
+ let expectation = expectationWithDescription("Download should be cancelled")
+
+ var request: NSURLRequest?
+ var response: NSHTTPURLResponse?
+ var data: AnyObject?
+ var error: NSError?
+
+ // When
+ let download = Alamofire.download(.GET, self.URLString, destination: self.destination)
+ .response { responseRequest, responseResponse, responseData, responseError in
+ request = responseRequest
+ response = responseResponse
+ data = responseData
+ error = responseError
+
+ expectation.fulfill()
+ }
+
+ download.cancel()
+
+ waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
+
+ // Then
+ XCTAssertNotNil(request, "request should not be nil")
+ XCTAssertNil(response, "response should be nil")
+ XCTAssertNil(data, "data should be nil") | Tests/DownloadTests.swift | 26 | Swift | 0.286 | question | 52 | 51 | 51 | false | Feature - Download Resume Data | 595 | Alamofire/Alamofire | 41,690 | Swift | kylef | cnoon |
let expectation = expectationWithDescription("Download should be cancelled")
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var data: AnyObject?
var error: NSError?
// When
let download = Alamofire.download(.GET, self.URLString, destination: self.destination)
.response { responseRequest, responseResponse, responseData, responseError in
request = responseRequest
response = responseResponse
data = responseData
error = responseError
expectation.fulfill()
}
download.cancel()
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNil(response, "response should be nil")
XCTAssertNil(data, "data should be nil")
XCTAssertNotNil(error, "error should not be nil")
}
func testThatCancelledDownloadResponseDataMatchesResumeData() {
// Given
let expectation = expectationWithDescription("Download should be cancelled")
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var data: AnyObject?
var error: NSError?
// When
let download = Alamofire.download(.GET, self.URLString, destination: self.destination)
download.progress { _, _, _ in
download.cancel()
}
download.response { responseRequest, responseResponse, responseData, responseError in
request = responseRequest
response = responseResponse
data = responseData
error = responseError
expectation.fulfill()
} | Yes it ABSOLUTELY should. Will fix.
| let expectation = expectationWithDescription("Download should be cancelled")
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var data: AnyObject?
var error: NSError?
// When
let download = Alamofire.download(.GET, self.URLString, destination: self.destination)
.response { responseRequest, responseResponse, responseData, responseError in
request = responseRequest
response = responseResponse
data = responseData
error = responseError
expectation.fulfill()
}
download.cancel()
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNil(response, "response should be nil")
XCTAssertNil(data, "data should be nil")
XCTAssertNotNil(error, "error should not be nil")
XCTAssertNil(download.resumeData, "resume data should be nil")
}
func testThatCancelledDownloadResponseDataMatchesResumeData() {
// Given
let expectation = expectationWithDescription("Download should be cancelled")
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var data: AnyObject?
var error: NSError?
// When
let download = Alamofire.download(.GET, self.URLString, destination: self.destination)
download.progress { _, _, _ in
download.cancel()
}
download.response { responseRequest, responseResponse, responseData, responseError in
request = responseRequest
response = responseResponse
data = responseData
error = responseError
| @@ -216,3 +212,123 @@ class DownloadResponseTestCase: BaseTestCase {
XCTAssertNil(removalError, "removal error should be nil")
}
}
+
+// MARK: -
+
+class DownloadResumeDataTestCase: BaseTestCase {
+ let URLString = "https://upload.wikimedia.org/wikipedia/commons/6/69/NASA-HS201427a-HubbleUltraDeepField2014-20140603.jpg"
+ let destination: Request.DownloadFileDestination = {
+ let searchPathDirectory: NSSearchPathDirectory = .CachesDirectory
+ let searchPathDomain: NSSearchPathDomainMask = .UserDomainMask
+
+ return Request.suggestedDownloadDestination(directory: searchPathDirectory, domain: searchPathDomain)
+ }()
+
+ func testThatImmediatelyCancelledDownloadDoesNotHaveResumeDataAvailable() {
+ // Given
+ let expectation = expectationWithDescription("Download should be cancelled")
+
+ var request: NSURLRequest?
+ var response: NSHTTPURLResponse?
+ var data: AnyObject?
+ var error: NSError?
+
+ // When
+ let download = Alamofire.download(.GET, self.URLString, destination: self.destination)
+ .response { responseRequest, responseResponse, responseData, responseError in
+ request = responseRequest
+ response = responseResponse
+ data = responseData
+ error = responseError
+
+ expectation.fulfill()
+ }
+
+ download.cancel()
+
+ waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
+
+ // Then
+ XCTAssertNotNil(request, "request should not be nil")
+ XCTAssertNil(response, "response should be nil")
+ XCTAssertNil(data, "data should be nil") | Tests/DownloadTests.swift | 26 | Swift | 0.143 | suggestion | 36 | 51 | 51 | false | Feature - Download Resume Data | 595 | Alamofire/Alamofire | 41,690 | Swift | cnoon | cnoon |
// ResponseSerialization.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
// MARK: ResponseSerializer
/**
The type in which all response serializers must conform to in order to serialize a response.
*/
public protocol ResponseSerializer {
/// The type of serialized object to be created by this `ResponseSerializer`.
typealias SerializedObject
/**
A closure used by response handlers that takes a request, response, and data and returns a result.
*/
var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?) -> Result<SerializedObject> { get }
}
// MARK: -
/**
A generic `ResponseSerializer` used to serialize a request, response, and data into a serialized object.
*/
public struct GenericResponseSerializer<T>: ResponseSerializer {
/// The type of serialized object to be created by this `ResponseSerializer`.
public typealias SerializedObject = T
/**
A closure used by response handlers that takes a request, response, and data and returns a result.
*/
public var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?) -> Result<SerializedObject>
/**
Initializes the `GenericResponseSerializer` instance with the given serialize response closure.
- parameter serializeResponse: The closure used to serialize the response.
- returns: The new generic response serializer instance.
*/
public init(serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?) -> Result<SerializedObject>) {
self.serializeResponse = serializeResponse
}
}
// MARK: - Default
extension Request {
/**
Adds a handler to be called once the request has finished.
- parameter queue: The queue on which the completion handler is dispatched.
- parameter completionHandler: The code to be executed once the request has finished.
- returns: The request.
*/
public func response(
queue queue: dispatch_queue_t? = nil,
completionHandler: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Void)
-> Self
{
delegate.queue.addOperationWithBlock {
dispatch_async(queue ?? dispatch_get_main_queue()) {
completionHandler(self.request, self.response, self.delegate.data, self.delegate.error)
}
}
return self
}
/**
Adds a handler to be called once the request has finished.
- parameter queue: The queue on which the completion handler is dispatched.
- parameter responseSerializer: The response serializer responsible for serializing the request, response,
and data.
- parameter completionHandler: The code to be executed once the request has finished.
- returns: The request.
*/
public func response<T: ResponseSerializer, V where T.SerializedObject == V>(
queue queue: dispatch_queue_t? = nil,
responseSerializer: T,
completionHandler: (NSURLRequest?, NSHTTPURLResponse?, Result<V>) -> Void)
-> Self
{
delegate.queue.addOperationWithBlock {
let result: Result<T.SerializedObject> = {
if let error = self.delegate.error {
return .Failure(self.delegate.data, error)
} else {
return responseSerializer.serializeResponse(self.request, self.response, self.delegate.data)
}
}()
dispatch_async(queue ?? dispatch_get_main_queue()) {
completionHandler(self.request, self.response, result)
}
}
return self
}
}
// MARK: - Data
extension Request {
/**
Creates a response serializer that returns the associated data as-is.
- returns: A data response serializer.
*/
public static func dataResponseSerializer() -> GenericResponseSerializer<NSData> {
return GenericResponseSerializer { _, _, data in
guard let validData = data else {
let failureReason = "Data could not be serialized. Input data was nil."
let error = Error.errorWithCode(.DataSerializationFailed, failureReason: failureReason)
return .Failure(data, error)
}
return .Success(validData)
}
}
/**
Adds a handler to be called once the request has finished.
- parameter completionHandler: The code to be executed once the request has finished.
- returns: The request.
*/
public func responseData(completionHandler: (NSURLRequest?, NSHTTPURLResponse?, Result<NSData>) -> Void) -> Self {
return response(responseSerializer: Request.dataResponseSerializer(), completionHandler: completionHandler)
}
}
// MARK: - String
extension Request {
/**
Creates a response serializer that returns a string initialized from the response data with the specified
string encoding.
- parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server
response, falling back to the default HTTP default character set, ISO-8859-1.
- returns: A string response serializer.
*/
public static func stringResponseSerializer(
var encoding encoding: NSStringEncoding? = nil)
-> GenericResponseSerializer<String>
{
return GenericResponseSerializer { _, response, data in
guard let validData = data else {
let failureReason = "String could not be serialized because input data was nil."
let error = Error.errorWithCode(.StringSerializationFailed, failureReason: failureReason)
return .Failure(data, error)
}
if let encodingName = response?.textEncodingName where encoding == nil {
encoding = CFStringConvertEncodingToNSStringEncoding(
CFStringConvertIANACharSetNameToEncoding(encodingName)
)
}
let actualEncoding = encoding ?? NSISOLatin1StringEncoding
if let string = NSString(data: validData, encoding: actualEncoding) as? String {
return .Success(string)
} else {
let failureReason = "String could not be serialized with encoding: \(actualEncoding)"
let error = Error.errorWithCode(.StringSerializationFailed, failureReason: failureReason)
return .Failure(data, error)
}
}
}
/**
Adds a handler to be called once the request has finished.
- parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the
server response, falling back to the default HTTP default character set,
ISO-8859-1.
- parameter completionHandler: A closure to be executed once the request has finished. The closure takes 3
arguments: the URL request, the URL response and the result produced while
creating the string.
- returns: The request.
*/
public func responseString(
encoding encoding: NSStringEncoding? = nil,
completionHandler: (NSURLRequest?, NSHTTPURLResponse?, Result<String>) -> Void)
-> Self
{
return response(
responseSerializer: Request.stringResponseSerializer(encoding: encoding),
completionHandler: completionHandler
)
}
}
// MARK: - JSON
extension Request {
/**
Creates a response serializer that returns a JSON object constructed from the response data using
`NSJSONSerialization` with the specified reading options.
- parameter options: The JSON serialization reading options. `.AllowFragments` by default.
- returns: A JSON object response serializer.
*/
public static func JSONResponseSerializer(
options options: NSJSONReadingOptions = .AllowFragments)
-> GenericResponseSerializer<AnyObject>
{
return GenericResponseSerializer { _, _, data in
guard let validData = data else {
let failureReason = "JSON could not be serialized because input data was nil."
let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason)
return .Failure(data, error)
}
do {
let JSON = try NSJSONSerialization.JSONObjectWithData(validData, options: options)
return .Success(JSON)
} catch {
return .Failure(data, error as NSError)
}
}
}
/**
Adds a handler to be called once the request has finished.
- parameter options: The JSON serialization reading options. `.AllowFragments` by default.
- parameter completionHandler: A closure to be executed once the request has finished. The closure takes 3
arguments: the URL request, the URL response and the result produced while
creating the JSON object.
- returns: The request.
*/
public func responseJSON(
options options: NSJSONReadingOptions = .AllowFragments,
completionHandler: (NSURLRequest?, NSHTTPURLResponse?, Result<AnyObject>) -> Void)
-> Self
{
return response(
responseSerializer: Request.JSONResponseSerializer(options: options),
completionHandler: completionHandler
)
}
}
// MARK: - Property List
extension Request {
/**
Creates a response serializer that returns an object constructed from the response data using
`NSPropertyListSerialization` with the specified reading options.
- parameter options: The property list reading options. `NSPropertyListReadOptions()` by default.
- returns: A property list object response serializer.
*/
public static func propertyListResponseSerializer(
options options: NSPropertyListReadOptions = NSPropertyListReadOptions())
-> GenericResponseSerializer<AnyObject>
{
return GenericResponseSerializer { _, _, data in
guard let validData = data else {
let failureReason = "Property list could not be serialized because input data was nil."
let error = Error.errorWithCode(.PropertyListSerializationFailed, failureReason: failureReason)
return .Failure(data, error)
}
do {
let plist = try NSPropertyListSerialization.propertyListWithData(validData, options: options, format: nil)
return .Success(plist)
} catch {
return .Failure(data, error as NSError)
}
}
}
/**
Adds a handler to be called once the request has finished.
- parameter options: The property list reading options. `0` by default.
- parameter completionHandler: A closure to be executed once the request has finished. The closure takes 3
arguments: the URL request, the URL response and the result produced while
creating the property list.
- returns: The request.
*/
public func responsePropertyList(
options options: NSPropertyListReadOptions = NSPropertyListReadOptions(),
completionHandler: (NSURLRequest?, NSHTTPURLResponse?, Result<AnyObject>) -> Void)
-> Self
{
return response(
responseSerializer: Request.propertyListResponseSerializer(options: options),
completionHandler: completionHandler
)
}
}
| Could you kill this extra newline?
| // ResponseSerialization.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
// MARK: ResponseSerializer
/**
The type in which all response serializers must conform to in order to serialize a response.
*/
public protocol ResponseSerializer {
/// The type of serialized object to be created by this `ResponseSerializer`.
typealias SerializedObject
/**
A closure used by response handlers that takes a request, response, and data and returns a result.
*/
var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?) -> Result<SerializedObject> { get }
}
// MARK: -
/**
A generic `ResponseSerializer` used to serialize a request, response, and data into a serialized object.
*/
public struct GenericResponseSerializer<T>: ResponseSerializer {
/// The type of serialized object to be created by this `ResponseSerializer`.
public typealias SerializedObject = T
/**
A closure used by response handlers that takes a request, response, and data and returns a result.
*/
public var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?) -> Result<SerializedObject>
/**
Initializes the `GenericResponseSerializer` instance with the given serialize response closure.
- parameter serializeResponse: The closure used to serialize the response.
- returns: The new generic response serializer instance.
*/
public init(serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?) -> Result<SerializedObject>) {
self.serializeResponse = serializeResponse
}
}
// MARK: - Default
extension Request {
/**
Adds a handler to be called once the request has finished.
- parameter queue: The queue on which the completion handler is dispatched.
- parameter completionHandler: The code to be executed once the request has finished.
- returns: The request.
*/
public func response(
queue queue: dispatch_queue_t? = nil,
completionHandler: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Void)
-> Self
{
delegate.queue.addOperationWithBlock {
dispatch_async(queue ?? dispatch_get_main_queue()) {
completionHandler(self.request, self.response, self.delegate.data, self.delegate.error)
}
}
return self
}
/**
Adds a handler to be called once the request has finished.
- parameter queue: The queue on which the completion handler is dispatched.
- parameter responseSerializer: The response serializer responsible for serializing the request, response,
and data.
- parameter completionHandler: The code to be executed once the request has finished.
- returns: The request.
*/
public func response<T: ResponseSerializer, V where T.SerializedObject == V>(
queue queue: dispatch_queue_t? = nil,
responseSerializer: T,
completionHandler: (NSURLRequest?, NSHTTPURLResponse?, Result<V>) -> Void)
-> Self
{
delegate.queue.addOperationWithBlock {
let result: Result<T.SerializedObject> = {
if let error = self.delegate.error {
return .Failure(self.delegate.data, error)
} else {
return responseSerializer.serializeResponse(self.request, self.response, self.delegate.data)
}
}()
dispatch_async(queue ?? dispatch_get_main_queue()) {
completionHandler(self.request, self.response, result)
}
}
return self
}
}
// MARK: - Data
extension Request {
/**
Creates a response serializer that returns the associated data as-is.
- returns: A data response serializer.
*/
public static func dataResponseSerializer() -> GenericResponseSerializer<NSData> {
return GenericResponseSerializer { _, _, data in
guard let validData = data else {
let failureReason = "Data could not be serialized. Input data was nil."
let error = Error.errorWithCode(.DataSerializationFailed, failureReason: failureReason)
return .Failure(data, error)
}
return .Success(validData)
}
}
/**
Adds a handler to be called once the request has finished.
- parameter completionHandler: The code to be executed once the request has finished.
- returns: The request.
*/
public func responseData(completionHandler: (NSURLRequest?, NSHTTPURLResponse?, Result<NSData>) -> Void) -> Self {
return response(responseSerializer: Request.dataResponseSerializer(), completionHandler: completionHandler)
}
}
// MARK: - String
extension Request {
/**
Creates a response serializer that returns a string initialized from the response data with the specified
string encoding.
- parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server
response, falling back to the default HTTP default character set, ISO-8859-1.
- returns: A string response serializer.
*/
public static func stringResponseSerializer(
var encoding encoding: NSStringEncoding? = nil)
-> GenericResponseSerializer<String>
{
return GenericResponseSerializer { _, response, data in
guard let validData = data else {
let failureReason = "String could not be serialized because input data was nil."
let error = Error.errorWithCode(.StringSerializationFailed, failureReason: failureReason)
return .Failure(data, error)
}
if let encodingName = response?.textEncodingName where encoding == nil {
encoding = CFStringConvertEncodingToNSStringEncoding(
CFStringConvertIANACharSetNameToEncoding(encodingName)
)
}
let actualEncoding = encoding ?? NSISOLatin1StringEncoding
if let string = NSString(data: validData, encoding: actualEncoding) as? String {
return .Success(string)
} else {
let failureReason = "String could not be serialized with encoding: \(actualEncoding)"
let error = Error.errorWithCode(.StringSerializationFailed, failureReason: failureReason)
return .Failure(data, error)
}
}
}
/**
Adds a handler to be called once the request has finished.
- parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the
server response, falling back to the default HTTP default character set,
ISO-8859-1.
- parameter completionHandler: A closure to be executed once the request has finished. The closure takes 3
arguments: the URL request, the URL response and the result produced while
creating the string.
- returns: The request.
*/
public func responseString(
encoding encoding: NSStringEncoding? = nil,
completionHandler: (NSURLRequest?, NSHTTPURLResponse?, Result<String>) -> Void)
-> Self
{
return response(
responseSerializer: Request.stringResponseSerializer(encoding: encoding),
completionHandler: completionHandler
)
}
}
// MARK: - JSON
extension Request {
/**
Creates a response serializer that returns a JSON object constructed from the response data using
`NSJSONSerialization` with the specified reading options.
- parameter options: The JSON serialization reading options. `.AllowFragments` by default.
- returns: A JSON object response serializer.
*/
public static func JSONResponseSerializer(
options options: NSJSONReadingOptions = .AllowFragments)
-> GenericResponseSerializer<AnyObject>
{
return GenericResponseSerializer { _, _, data in
guard let validData = data else {
let failureReason = "JSON could not be serialized because input data was nil."
let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason)
return .Failure(data, error)
}
do {
let JSON = try NSJSONSerialization.JSONObjectWithData(validData, options: options)
return .Success(JSON)
} catch {
return .Failure(data, error as NSError)
}
}
}
/**
Adds a handler to be called once the request has finished.
- parameter options: The JSON serialization reading options. `.AllowFragments` by default.
- parameter completionHandler: A closure to be executed once the request has finished. The closure takes 3
arguments: the URL request, the URL response and the result produced while
creating the JSON object.
- returns: The request.
*/
public func responseJSON(
options options: NSJSONReadingOptions = .AllowFragments,
completionHandler: (NSURLRequest?, NSHTTPURLResponse?, Result<AnyObject>) -> Void)
-> Self
{
return response(
responseSerializer: Request.JSONResponseSerializer(options: options),
completionHandler: completionHandler
)
}
}
// MARK: - Property List
extension Request {
/**
Creates a response serializer that returns an object constructed from the response data using
`NSPropertyListSerialization` with the specified reading options.
- parameter options: The property list reading options. `NSPropertyListReadOptions()` by default.
- returns: A property list object response serializer.
*/
public static func propertyListResponseSerializer(
options options: NSPropertyListReadOptions = NSPropertyListReadOptions())
-> GenericResponseSerializer<AnyObject>
{
return GenericResponseSerializer { _, _, data in
guard let validData = data else {
let failureReason = "Property list could not be serialized because input data was nil."
let error = Error.errorWithCode(.PropertyListSerializationFailed, failureReason: failureReason)
return .Failure(data, error)
}
do {
let plist = try NSPropertyListSerialization.propertyListWithData(validData, options: options, format: nil)
return .Success(plist)
} catch {
return .Failure(data, error as NSError)
}
}
}
/**
Adds a handler to be called once the request has finished.
- parameter options: The property list reading options. `0` by default.
- parameter completionHandler: A closure to be executed once the request has finished. The closure takes 3
arguments: the URL request, the URL response and the result produced while
creating the property list.
- returns: The request.
*/
public func responsePropertyList(
options options: NSPropertyListReadOptions = NSPropertyListReadOptions(),
completionHandler: (NSURLRequest?, NSHTTPURLResponse?, Result<AnyObject>) -> Void)
-> Self
{
return response(
responseSerializer: Request.propertyListResponseSerializer(options: options),
completionHandler: completionHandler
)
}
}
| @@ -106,11 +106,14 @@ extension Request {
-> Self
{
delegate.queue.addOperationWithBlock {
- var result = responseSerializer.serializeResponse(self.request, self.response, self.delegate.data)
-
- if let error = self.delegate.error {
- result = .Failure(self.delegate.data, error)
- }
+ | Source/ResponseSerialization.swift | 0 | Swift | 0.143 | question | 35 | 333 | 332 | false | Update ResponseSerialization.swift | 716 | Alamofire/Alamofire | 41,690 | Swift | cnoon | brocoo |
// ResponseSerializationTests.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Alamofire
import Foundation
import XCTest
class ResponseSerializationTestCase: BaseTestCase {
let error = NSError(domain: Error.Domain, code: -10000, userInfo: nil)
// MARK: - Data Response Serializer Tests
func testThatDataResponseSerializerSucceedsWhenDataIsNotNil() {
// Given
let serializer = Request.dataResponseSerializer()
let data = "data".dataUsingEncoding(NSUTF8StringEncoding)!
// When
let result = serializer.serializeResponse(nil, nil, data, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
}
func testThatDataResponseSerializerFailsWhenDataIsNil() {
// Given
let serializer = Request.dataResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, nil, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.DataSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatDataResponseSerializerFailsWhenErrorIsNotNil() {
// Given
let serializer = Request.dataResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, nil, error)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, self.error.code, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatDataResponseSerializerFailsWhenDataIsNilWithNon204ResponseStatusCode() {
// Given
let serializer = Request.dataResponseSerializer()
let URL = NSURL(string: "https://httpbin.org/get")!
let response = NSHTTPURLResponse(URL: URL, statusCode: 200, HTTPVersion: "HTTP/1.1", headerFields: nil)
// When
let result = serializer.serializeResponse(nil, response, nil, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.DataSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatDataResponseSerializerSucceedsWhenDataIsNilWith204ResponseStatusCode() {
// Given
let serializer = Request.dataResponseSerializer()
let URL = NSURL(string: "https://httpbin.org/get")!
let response = NSHTTPURLResponse(URL: URL, statusCode: 204, HTTPVersion: "HTTP/1.1", headerFields: nil)
// When
let result = serializer.serializeResponse(nil, response, nil, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
if let data = result.value {
XCTAssertEqual(data.length, 0, "data length should be zero")
}
}
// MARK: - String Response Serializer Tests
func testThatStringResponseSerializerFailsWhenDataIsNil() {
// Given
let serializer = Request.stringResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, nil, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.StringSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatStringResponseSerializerSucceedsWhenDataIsEmpty() {
// Given
let serializer = Request.stringResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, NSData(), nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
}
func testThatStringResponseSerializerSucceedsWithUTF8DataAndNoProvidedEncoding() {
let serializer = Request.stringResponseSerializer()
let data = "data".dataUsingEncoding(NSUTF8StringEncoding)!
// When
let result = serializer.serializeResponse(nil, nil, data, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
}
func testThatStringResponseSerializerSucceedsWithUTF8DataAndUTF8ProvidedEncoding() {
let serializer = Request.stringResponseSerializer(encoding: NSUTF8StringEncoding)
let data = "data".dataUsingEncoding(NSUTF8StringEncoding)!
// When
let result = serializer.serializeResponse(nil, nil, data, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
}
func testThatStringResponseSerializerSucceedsWithUTF8DataUsingResponseTextEncodingName() {
let serializer = Request.stringResponseSerializer()
let data = "data".dataUsingEncoding(NSUTF8StringEncoding)!
let response = NSHTTPURLResponse(
URL: NSURL(string: "https://httpbin.org/get")!,
statusCode: 200,
HTTPVersion: "HTTP/1.1",
headerFields: ["Content-Type": "image/jpeg; charset=utf-8"]
)
// When
let result = serializer.serializeResponse(nil, response, data, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
}
func testThatStringResponseSerializerFailsWithUTF32DataAndUTF8ProvidedEncoding() {
// Given
let serializer = Request.stringResponseSerializer(encoding: NSUTF8StringEncoding)
let data = "random data".dataUsingEncoding(NSUTF32StringEncoding)!
// When
let result = serializer.serializeResponse(nil, nil, data, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.StringSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatStringResponseSerializerFailsWithUTF32DataAndUTF8ResponseEncoding() {
// Given
let serializer = Request.stringResponseSerializer()
let data = "random data".dataUsingEncoding(NSUTF32StringEncoding)!
let response = NSHTTPURLResponse(
URL: NSURL(string: "https://httpbin.org/get")!,
statusCode: 200,
HTTPVersion: "HTTP/1.1",
headerFields: ["Content-Type": "image/jpeg; charset=utf-8"]
)
// When
let result = serializer.serializeResponse(nil, response, data, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.StringSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatStringResponseSerializerFailsWhenErrorIsNotNil() {
// Given
let serializer = Request.stringResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, nil, error)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, self.error.code, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatStringResponseSerializerFailsWhenDataIsNilWithNon204ResponseStatusCode() {
// Given
let serializer = Request.stringResponseSerializer()
let URL = NSURL(string: "https://httpbin.org/get")!
let response = NSHTTPURLResponse(URL: URL, statusCode: 200, HTTPVersion: "HTTP/1.1", headerFields: nil)
// When
let result = serializer.serializeResponse(nil, response, nil, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.StringSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatStringResponseSerializerSucceedsWhenDataIsNilWith204ResponseStatusCode() {
// Given
let serializer = Request.stringResponseSerializer()
let URL = NSURL(string: "https://httpbin.org/get")!
let response = NSHTTPURLResponse(URL: URL, statusCode: 204, HTTPVersion: "HTTP/1.1", headerFields: nil)
// When
let result = serializer.serializeResponse(nil, response, nil, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
if let string = result.value {
XCTAssertEqual(string, "", "string should be equal to empty string")
}
}
// MARK: - JSON Response Serializer Tests
func testThatJSONResponseSerializerFailsWhenDataIsNil() {
// Given
let serializer = Request.JSONResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, nil, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.JSONSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatJSONResponseSerializerFailsWhenDataIsEmpty() {
// Given
let serializer = Request.JSONResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, NSData(), nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, "NSCocoaErrorDomain", "error domain should match expected value")
XCTAssertEqual(error.code, 3840, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatJSONResponseSerializerSucceedsWhenDataIsValidJSON() {
// Given
let serializer = Request.stringResponseSerializer()
let data = "{\"json\": true}".dataUsingEncoding(NSUTF8StringEncoding)!
// When
let result = serializer.serializeResponse(nil, nil, data, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
}
func testThatJSONResponseSerializerFailsWhenDataIsInvalidJSON() {
// Given
let serializer = Request.JSONResponseSerializer()
let data = "definitely not valid json".dataUsingEncoding(NSUTF8StringEncoding)!
// When
let result = serializer.serializeResponse(nil, nil, data, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, NSCocoaErrorDomain, "error domain should match expected value")
XCTAssertEqual(error.code, 3840, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatJSONResponseSerializerFailsWhenErrorIsNotNil() {
// Given
let serializer = Request.JSONResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, nil, error)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, self.error.code, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatJSONResponseSerializerFailsWhenDataIsNilWithNon204ResponseStatusCode() {
// Given
let serializer = Request.JSONResponseSerializer()
let URL = NSURL(string: "https://httpbin.org/get")!
let response = NSHTTPURLResponse(URL: URL, statusCode: 200, HTTPVersion: "HTTP/1.1", headerFields: nil)
// When
let result = serializer.serializeResponse(nil, response, nil, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.JSONSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatJSONResponseSerializerSucceedsWhenDataIsNilWith204ResponseStatusCode() {
// Given
let serializer = Request.JSONResponseSerializer()
let URL = NSURL(string: "https://httpbin.org/get")!
let response = NSHTTPURLResponse(URL: URL, statusCode: 204, HTTPVersion: "HTTP/1.1", headerFields: nil)
// When
let result = serializer.serializeResponse(nil, response, nil, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
if let json = result.value as? NSNull {
XCTAssertEqual(json, NSNull(), "json should be equal to NSNull")
}
}
// MARK: - Property List Response Serializer Tests
func testThatPropertyListResponseSerializerFailsWhenDataIsNil() {
// Given
let serializer = Request.propertyListResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, nil, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.PropertyListSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatPropertyListResponseSerializerFailsWhenDataIsEmpty() {
// Given
let serializer = Request.propertyListResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, NSData(), nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, "NSCocoaErrorDomain", "error domain should match expected value")
XCTAssertEqual(error.code, 3840, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatPropertyListResponseSerializerSucceedsWhenDataIsValidPropertyListData() {
// Given
let serializer = Request.propertyListResponseSerializer()
let data = NSKeyedArchiver.archivedDataWithRootObject(["foo": "bar"])
// When
let result = serializer.serializeResponse(nil, nil, data, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
}
func testThatPropertyListResponseSerializerFailsWhenDataIsInvalidPropertyListData() {
// Given
let serializer = Request.propertyListResponseSerializer()
let data = "definitely not valid plist data".dataUsingEncoding(NSUTF8StringEncoding)!
// When
let result = serializer.serializeResponse(nil, nil, data, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, NSCocoaErrorDomain, "error domain should match expected value")
XCTAssertEqual(error.code, 3840, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatPropertyListResponseSerializerFailsWhenErrorIsNotNil() {
// Given
let serializer = Request.propertyListResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, nil, error)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, self.error.code, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatPropertyListResponseSerializerFailsWhenDataIsNilWithNon204ResponseStatusCode() {
// Given
let serializer = Request.propertyListResponseSerializer()
let URL = NSURL(string: "https://httpbin.org/get")!
let response = NSHTTPURLResponse(URL: URL, statusCode: 200, HTTPVersion: "HTTP/1.1", headerFields: nil)
// When
let result = serializer.serializeResponse(nil, response, nil, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.PropertyListSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatPropertyListResponseSerializerSucceedsWhenDataIsNilWith204ResponseStatusCode() {
// Given
let serializer = Request.propertyListResponseSerializer()
let URL = NSURL(string: "https://httpbin.org/get")!
let response = NSHTTPURLResponse(URL: URL, statusCode: 204, HTTPVersion: "HTTP/1.1", headerFields: nil)
// When
let result = serializer.serializeResponse(nil, response, nil, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
if let plist = result.value as? NSNull {
XCTAssertEqual(plist, NSNull(), "plist should be equal to NSNull")
}
}
}
| Can't we use the constant for [`NSCocoaErrorDomain`](https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Constants/index.html#//apple_ref/doc/c_ref/NSCocoaErrorDomain)?
| // ResponseSerializationTests.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Alamofire
import Foundation
import XCTest
class ResponseSerializationTestCase: BaseTestCase {
let error = NSError(domain: Error.Domain, code: -10000, userInfo: nil)
// MARK: - Data Response Serializer Tests
func testThatDataResponseSerializerSucceedsWhenDataIsNotNil() {
// Given
let serializer = Request.dataResponseSerializer()
let data = "data".dataUsingEncoding(NSUTF8StringEncoding)!
// When
let result = serializer.serializeResponse(nil, nil, data, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
}
func testThatDataResponseSerializerFailsWhenDataIsNil() {
// Given
let serializer = Request.dataResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, nil, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.DataSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatDataResponseSerializerFailsWhenErrorIsNotNil() {
// Given
let serializer = Request.dataResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, nil, error)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, self.error.code, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatDataResponseSerializerFailsWhenDataIsNilWithNon204ResponseStatusCode() {
// Given
let serializer = Request.dataResponseSerializer()
let URL = NSURL(string: "https://httpbin.org/get")!
let response = NSHTTPURLResponse(URL: URL, statusCode: 200, HTTPVersion: "HTTP/1.1", headerFields: nil)
// When
let result = serializer.serializeResponse(nil, response, nil, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.DataSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatDataResponseSerializerSucceedsWhenDataIsNilWith204ResponseStatusCode() {
// Given
let serializer = Request.dataResponseSerializer()
let URL = NSURL(string: "https://httpbin.org/get")!
let response = NSHTTPURLResponse(URL: URL, statusCode: 204, HTTPVersion: "HTTP/1.1", headerFields: nil)
// When
let result = serializer.serializeResponse(nil, response, nil, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
if let data = result.value {
XCTAssertEqual(data.length, 0, "data length should be zero")
}
}
// MARK: - String Response Serializer Tests
func testThatStringResponseSerializerFailsWhenDataIsNil() {
// Given
let serializer = Request.stringResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, nil, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.StringSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatStringResponseSerializerSucceedsWhenDataIsEmpty() {
// Given
let serializer = Request.stringResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, NSData(), nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
}
func testThatStringResponseSerializerSucceedsWithUTF8DataAndNoProvidedEncoding() {
let serializer = Request.stringResponseSerializer()
let data = "data".dataUsingEncoding(NSUTF8StringEncoding)!
// When
let result = serializer.serializeResponse(nil, nil, data, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
}
func testThatStringResponseSerializerSucceedsWithUTF8DataAndUTF8ProvidedEncoding() {
let serializer = Request.stringResponseSerializer(encoding: NSUTF8StringEncoding)
let data = "data".dataUsingEncoding(NSUTF8StringEncoding)!
// When
let result = serializer.serializeResponse(nil, nil, data, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
}
func testThatStringResponseSerializerSucceedsWithUTF8DataUsingResponseTextEncodingName() {
let serializer = Request.stringResponseSerializer()
let data = "data".dataUsingEncoding(NSUTF8StringEncoding)!
let response = NSHTTPURLResponse(
URL: NSURL(string: "https://httpbin.org/get")!,
statusCode: 200,
HTTPVersion: "HTTP/1.1",
headerFields: ["Content-Type": "image/jpeg; charset=utf-8"]
)
// When
let result = serializer.serializeResponse(nil, response, data, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
}
func testThatStringResponseSerializerFailsWithUTF32DataAndUTF8ProvidedEncoding() {
// Given
let serializer = Request.stringResponseSerializer(encoding: NSUTF8StringEncoding)
let data = "random data".dataUsingEncoding(NSUTF32StringEncoding)!
// When
let result = serializer.serializeResponse(nil, nil, data, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.StringSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatStringResponseSerializerFailsWithUTF32DataAndUTF8ResponseEncoding() {
// Given
let serializer = Request.stringResponseSerializer()
let data = "random data".dataUsingEncoding(NSUTF32StringEncoding)!
let response = NSHTTPURLResponse(
URL: NSURL(string: "https://httpbin.org/get")!,
statusCode: 200,
HTTPVersion: "HTTP/1.1",
headerFields: ["Content-Type": "image/jpeg; charset=utf-8"]
)
// When
let result = serializer.serializeResponse(nil, response, data, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.StringSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatStringResponseSerializerFailsWhenErrorIsNotNil() {
// Given
let serializer = Request.stringResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, nil, error)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, self.error.code, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatStringResponseSerializerFailsWhenDataIsNilWithNon204ResponseStatusCode() {
// Given
let serializer = Request.stringResponseSerializer()
let URL = NSURL(string: "https://httpbin.org/get")!
let response = NSHTTPURLResponse(URL: URL, statusCode: 200, HTTPVersion: "HTTP/1.1", headerFields: nil)
// When
let result = serializer.serializeResponse(nil, response, nil, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.StringSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatStringResponseSerializerSucceedsWhenDataIsNilWith204ResponseStatusCode() {
// Given
let serializer = Request.stringResponseSerializer()
let URL = NSURL(string: "https://httpbin.org/get")!
let response = NSHTTPURLResponse(URL: URL, statusCode: 204, HTTPVersion: "HTTP/1.1", headerFields: nil)
// When
let result = serializer.serializeResponse(nil, response, nil, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
if let string = result.value {
XCTAssertEqual(string, "", "string should be equal to empty string")
}
}
// MARK: - JSON Response Serializer Tests
func testThatJSONResponseSerializerFailsWhenDataIsNil() {
// Given
let serializer = Request.JSONResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, nil, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.JSONSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatJSONResponseSerializerFailsWhenDataIsEmpty() {
// Given
let serializer = Request.JSONResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, NSData(), nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.JSONSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatJSONResponseSerializerSucceedsWhenDataIsValidJSON() {
// Given
let serializer = Request.stringResponseSerializer()
let data = "{\"json\": true}".dataUsingEncoding(NSUTF8StringEncoding)!
// When
let result = serializer.serializeResponse(nil, nil, data, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
}
func testThatJSONResponseSerializerFailsWhenDataIsInvalidJSON() {
// Given
let serializer = Request.JSONResponseSerializer()
let data = "definitely not valid json".dataUsingEncoding(NSUTF8StringEncoding)!
// When
let result = serializer.serializeResponse(nil, nil, data, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, NSCocoaErrorDomain, "error domain should match expected value")
XCTAssertEqual(error.code, 3840, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatJSONResponseSerializerFailsWhenErrorIsNotNil() {
// Given
let serializer = Request.JSONResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, nil, error)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, self.error.code, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatJSONResponseSerializerFailsWhenDataIsNilWithNon204ResponseStatusCode() {
// Given
let serializer = Request.JSONResponseSerializer()
let URL = NSURL(string: "https://httpbin.org/get")!
let response = NSHTTPURLResponse(URL: URL, statusCode: 200, HTTPVersion: "HTTP/1.1", headerFields: nil)
// When
let result = serializer.serializeResponse(nil, response, nil, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.JSONSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatJSONResponseSerializerSucceedsWhenDataIsNilWith204ResponseStatusCode() {
// Given
let serializer = Request.JSONResponseSerializer()
let URL = NSURL(string: "https://httpbin.org/get")!
let response = NSHTTPURLResponse(URL: URL, statusCode: 204, HTTPVersion: "HTTP/1.1", headerFields: nil)
// When
let result = serializer.serializeResponse(nil, response, nil, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
if let json = result.value as? NSNull {
XCTAssertEqual(json, NSNull(), "json should be equal to NSNull")
}
}
// MARK: - Property List Response Serializer Tests
func testThatPropertyListResponseSerializerFailsWhenDataIsNil() {
// Given
let serializer = Request.propertyListResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, nil, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.PropertyListSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatPropertyListResponseSerializerFailsWhenDataIsEmpty() {
// Given
let serializer = Request.propertyListResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, NSData(), nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.PropertyListSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatPropertyListResponseSerializerSucceedsWhenDataIsValidPropertyListData() {
// Given
let serializer = Request.propertyListResponseSerializer()
let data = NSKeyedArchiver.archivedDataWithRootObject(["foo": "bar"])
// When
let result = serializer.serializeResponse(nil, nil, data, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
}
func testThatPropertyListResponseSerializerFailsWhenDataIsInvalidPropertyListData() {
// Given
let serializer = Request.propertyListResponseSerializer()
let data = "definitely not valid plist data".dataUsingEncoding(NSUTF8StringEncoding)!
// When
let result = serializer.serializeResponse(nil, nil, data, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, NSCocoaErrorDomain, "error domain should match expected value")
XCTAssertEqual(error.code, 3840, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatPropertyListResponseSerializerFailsWhenErrorIsNotNil() {
// Given
let serializer = Request.propertyListResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, nil, error)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, self.error.code, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatPropertyListResponseSerializerFailsWhenDataIsNilWithNon204ResponseStatusCode() {
// Given
let serializer = Request.propertyListResponseSerializer()
let URL = NSURL(string: "https://httpbin.org/get")!
let response = NSHTTPURLResponse(URL: URL, statusCode: 200, HTTPVersion: "HTTP/1.1", headerFields: nil)
// When
let result = serializer.serializeResponse(nil, response, nil, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.PropertyListSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatPropertyListResponseSerializerSucceedsWhenDataIsNilWith204ResponseStatusCode() {
// Given
let serializer = Request.propertyListResponseSerializer()
let URL = NSURL(string: "https://httpbin.org/get")!
let response = NSHTTPURLResponse(URL: URL, statusCode: 204, HTTPVersion: "HTTP/1.1", headerFields: nil)
// When
let result = serializer.serializeResponse(nil, response, nil, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
if let plist = result.value as? NSNull {
XCTAssertEqual(plist, NSNull(), "plist should be equal to NSNull")
}
}
}
| @@ -266,8 +348,8 @@ class ResponseSerializationTestCase: BaseTestCase {
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
- XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
- XCTAssertEqual(error.code, Error.Code.JSONSerializationFailed.rawValue, "error code should match expected value")
+ XCTAssertEqual(error.domain, "NSCocoaErrorDomain", "error domain should match expected value") | Tests/ResponseSerializationTests.swift | 0 | Swift | 0.786 | question | 223 | 592 | 592 | false | Feature - Added 204 Support to Response Serializers | 889 | Alamofire/Alamofire | 41,690 | Swift | kylef | cnoon |
// ResponseSerializationTests.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Alamofire
import Foundation
import XCTest
class ResponseSerializationTestCase: BaseTestCase {
let error = NSError(domain: Error.Domain, code: -10000, userInfo: nil)
// MARK: - Data Response Serializer Tests
func testThatDataResponseSerializerSucceedsWhenDataIsNotNil() {
// Given
let serializer = Request.dataResponseSerializer()
let data = "data".dataUsingEncoding(NSUTF8StringEncoding)!
// When
let result = serializer.serializeResponse(nil, nil, data, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
}
func testThatDataResponseSerializerFailsWhenDataIsNil() {
// Given
let serializer = Request.dataResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, nil, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.DataSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatDataResponseSerializerFailsWhenErrorIsNotNil() {
// Given
let serializer = Request.dataResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, nil, error)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, self.error.code, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatDataResponseSerializerFailsWhenDataIsNilWithNon204ResponseStatusCode() {
// Given
let serializer = Request.dataResponseSerializer()
let URL = NSURL(string: "https://httpbin.org/get")!
let response = NSHTTPURLResponse(URL: URL, statusCode: 200, HTTPVersion: "HTTP/1.1", headerFields: nil)
// When
let result = serializer.serializeResponse(nil, response, nil, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.DataSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatDataResponseSerializerSucceedsWhenDataIsNilWith204ResponseStatusCode() {
// Given
let serializer = Request.dataResponseSerializer()
let URL = NSURL(string: "https://httpbin.org/get")!
let response = NSHTTPURLResponse(URL: URL, statusCode: 204, HTTPVersion: "HTTP/1.1", headerFields: nil)
// When
let result = serializer.serializeResponse(nil, response, nil, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
if let data = result.value {
XCTAssertEqual(data.length, 0, "data length should be zero")
}
}
// MARK: - String Response Serializer Tests
func testThatStringResponseSerializerFailsWhenDataIsNil() {
// Given
let serializer = Request.stringResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, nil, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.StringSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatStringResponseSerializerSucceedsWhenDataIsEmpty() {
// Given
let serializer = Request.stringResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, NSData(), nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
}
func testThatStringResponseSerializerSucceedsWithUTF8DataAndNoProvidedEncoding() {
let serializer = Request.stringResponseSerializer()
let data = "data".dataUsingEncoding(NSUTF8StringEncoding)!
// When
let result = serializer.serializeResponse(nil, nil, data, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
}
func testThatStringResponseSerializerSucceedsWithUTF8DataAndUTF8ProvidedEncoding() {
let serializer = Request.stringResponseSerializer(encoding: NSUTF8StringEncoding)
let data = "data".dataUsingEncoding(NSUTF8StringEncoding)!
// When
let result = serializer.serializeResponse(nil, nil, data, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
}
func testThatStringResponseSerializerSucceedsWithUTF8DataUsingResponseTextEncodingName() {
let serializer = Request.stringResponseSerializer()
let data = "data".dataUsingEncoding(NSUTF8StringEncoding)!
let response = NSHTTPURLResponse(
URL: NSURL(string: "https://httpbin.org/get")!,
statusCode: 200,
HTTPVersion: "HTTP/1.1",
headerFields: ["Content-Type": "image/jpeg; charset=utf-8"]
)
// When
let result = serializer.serializeResponse(nil, response, data, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
}
func testThatStringResponseSerializerFailsWithUTF32DataAndUTF8ProvidedEncoding() {
// Given
let serializer = Request.stringResponseSerializer(encoding: NSUTF8StringEncoding)
let data = "random data".dataUsingEncoding(NSUTF32StringEncoding)!
// When
let result = serializer.serializeResponse(nil, nil, data, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.StringSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatStringResponseSerializerFailsWithUTF32DataAndUTF8ResponseEncoding() {
// Given
let serializer = Request.stringResponseSerializer()
let data = "random data".dataUsingEncoding(NSUTF32StringEncoding)!
let response = NSHTTPURLResponse(
URL: NSURL(string: "https://httpbin.org/get")!,
statusCode: 200,
HTTPVersion: "HTTP/1.1",
headerFields: ["Content-Type": "image/jpeg; charset=utf-8"]
)
// When
let result = serializer.serializeResponse(nil, response, data, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.StringSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatStringResponseSerializerFailsWhenErrorIsNotNil() {
// Given
let serializer = Request.stringResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, nil, error)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, self.error.code, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatStringResponseSerializerFailsWhenDataIsNilWithNon204ResponseStatusCode() {
// Given
let serializer = Request.stringResponseSerializer()
let URL = NSURL(string: "https://httpbin.org/get")!
let response = NSHTTPURLResponse(URL: URL, statusCode: 200, HTTPVersion: "HTTP/1.1", headerFields: nil)
// When
let result = serializer.serializeResponse(nil, response, nil, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.StringSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatStringResponseSerializerSucceedsWhenDataIsNilWith204ResponseStatusCode() {
// Given
let serializer = Request.stringResponseSerializer()
let URL = NSURL(string: "https://httpbin.org/get")!
let response = NSHTTPURLResponse(URL: URL, statusCode: 204, HTTPVersion: "HTTP/1.1", headerFields: nil)
// When
let result = serializer.serializeResponse(nil, response, nil, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
if let string = result.value {
XCTAssertEqual(string, "", "string should be equal to empty string")
}
}
// MARK: - JSON Response Serializer Tests
func testThatJSONResponseSerializerFailsWhenDataIsNil() {
// Given
let serializer = Request.JSONResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, nil, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.JSONSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatJSONResponseSerializerFailsWhenDataIsEmpty() {
// Given
let serializer = Request.JSONResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, NSData(), nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, NSCocoaErrorDomain, "error domain should match expected value")
XCTAssertEqual(error.code, 3840, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatJSONResponseSerializerSucceedsWhenDataIsValidJSON() {
// Given
let serializer = Request.stringResponseSerializer()
let data = "{\"json\": true}".dataUsingEncoding(NSUTF8StringEncoding)!
// When
let result = serializer.serializeResponse(nil, nil, data, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
}
func testThatJSONResponseSerializerFailsWhenDataIsInvalidJSON() {
// Given
let serializer = Request.JSONResponseSerializer()
let data = "definitely not valid json".dataUsingEncoding(NSUTF8StringEncoding)!
// When
let result = serializer.serializeResponse(nil, nil, data, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, NSCocoaErrorDomain, "error domain should match expected value")
XCTAssertEqual(error.code, 3840, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatJSONResponseSerializerFailsWhenErrorIsNotNil() {
// Given
let serializer = Request.JSONResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, nil, error)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, self.error.code, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatJSONResponseSerializerFailsWhenDataIsNilWithNon204ResponseStatusCode() {
// Given
let serializer = Request.JSONResponseSerializer()
let URL = NSURL(string: "https://httpbin.org/get")!
let response = NSHTTPURLResponse(URL: URL, statusCode: 200, HTTPVersion: "HTTP/1.1", headerFields: nil)
// When
let result = serializer.serializeResponse(nil, response, nil, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.JSONSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatJSONResponseSerializerSucceedsWhenDataIsNilWith204ResponseStatusCode() {
// Given
let serializer = Request.JSONResponseSerializer()
let URL = NSURL(string: "https://httpbin.org/get")!
let response = NSHTTPURLResponse(URL: URL, statusCode: 204, HTTPVersion: "HTTP/1.1", headerFields: nil)
// When
let result = serializer.serializeResponse(nil, response, nil, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
if let json = result.value as? NSNull {
XCTAssertEqual(json, NSNull(), "json should be equal to NSNull")
}
}
// MARK: - Property List Response Serializer Tests
func testThatPropertyListResponseSerializerFailsWhenDataIsNil() {
// Given
let serializer = Request.propertyListResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, nil, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.PropertyListSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatPropertyListResponseSerializerFailsWhenDataIsEmpty() {
// Given
let serializer = Request.propertyListResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, NSData(), nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, NSCocoaErrorDomain, "error domain should match expected value")
XCTAssertEqual(error.code, 3840, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatPropertyListResponseSerializerSucceedsWhenDataIsValidPropertyListData() {
// Given
let serializer = Request.propertyListResponseSerializer()
let data = NSKeyedArchiver.archivedDataWithRootObject(["foo": "bar"])
// When
let result = serializer.serializeResponse(nil, nil, data, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
}
func testThatPropertyListResponseSerializerFailsWhenDataIsInvalidPropertyListData() {
// Given
let serializer = Request.propertyListResponseSerializer()
let data = "definitely not valid plist data".dataUsingEncoding(NSUTF8StringEncoding)!
// When
let result = serializer.serializeResponse(nil, nil, data, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, NSCocoaErrorDomain, "error domain should match expected value")
XCTAssertEqual(error.code, 3840, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatPropertyListResponseSerializerFailsWhenErrorIsNotNil() {
// Given
let serializer = Request.propertyListResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, nil, error)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, self.error.code, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatPropertyListResponseSerializerFailsWhenDataIsNilWithNon204ResponseStatusCode() {
// Given
let serializer = Request.propertyListResponseSerializer()
let URL = NSURL(string: "https://httpbin.org/get")!
let response = NSHTTPURLResponse(URL: URL, statusCode: 200, HTTPVersion: "HTTP/1.1", headerFields: nil)
// When
let result = serializer.serializeResponse(nil, response, nil, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.PropertyListSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatPropertyListResponseSerializerSucceedsWhenDataIsNilWith204ResponseStatusCode() {
// Given
let serializer = Request.propertyListResponseSerializer()
let URL = NSURL(string: "https://httpbin.org/get")!
let response = NSHTTPURLResponse(URL: URL, statusCode: 204, HTTPVersion: "HTTP/1.1", headerFields: nil)
// When
let result = serializer.serializeResponse(nil, response, nil, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
if let plist = result.value as? NSNull {
XCTAssertEqual(plist, NSNull(), "plist should be equal to NSNull")
}
}
}
| Isn't this `NSPropertyListReadCorruptError`? Seems like a Foundation bug raising a property list error for JSON.
| // ResponseSerializationTests.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Alamofire
import Foundation
import XCTest
class ResponseSerializationTestCase: BaseTestCase {
let error = NSError(domain: Error.Domain, code: -10000, userInfo: nil)
// MARK: - Data Response Serializer Tests
func testThatDataResponseSerializerSucceedsWhenDataIsNotNil() {
// Given
let serializer = Request.dataResponseSerializer()
let data = "data".dataUsingEncoding(NSUTF8StringEncoding)!
// When
let result = serializer.serializeResponse(nil, nil, data, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
}
func testThatDataResponseSerializerFailsWhenDataIsNil() {
// Given
let serializer = Request.dataResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, nil, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.DataSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatDataResponseSerializerFailsWhenErrorIsNotNil() {
// Given
let serializer = Request.dataResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, nil, error)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, self.error.code, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatDataResponseSerializerFailsWhenDataIsNilWithNon204ResponseStatusCode() {
// Given
let serializer = Request.dataResponseSerializer()
let URL = NSURL(string: "https://httpbin.org/get")!
let response = NSHTTPURLResponse(URL: URL, statusCode: 200, HTTPVersion: "HTTP/1.1", headerFields: nil)
// When
let result = serializer.serializeResponse(nil, response, nil, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.DataSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatDataResponseSerializerSucceedsWhenDataIsNilWith204ResponseStatusCode() {
// Given
let serializer = Request.dataResponseSerializer()
let URL = NSURL(string: "https://httpbin.org/get")!
let response = NSHTTPURLResponse(URL: URL, statusCode: 204, HTTPVersion: "HTTP/1.1", headerFields: nil)
// When
let result = serializer.serializeResponse(nil, response, nil, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
if let data = result.value {
XCTAssertEqual(data.length, 0, "data length should be zero")
}
}
// MARK: - String Response Serializer Tests
func testThatStringResponseSerializerFailsWhenDataIsNil() {
// Given
let serializer = Request.stringResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, nil, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.StringSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatStringResponseSerializerSucceedsWhenDataIsEmpty() {
// Given
let serializer = Request.stringResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, NSData(), nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
}
func testThatStringResponseSerializerSucceedsWithUTF8DataAndNoProvidedEncoding() {
let serializer = Request.stringResponseSerializer()
let data = "data".dataUsingEncoding(NSUTF8StringEncoding)!
// When
let result = serializer.serializeResponse(nil, nil, data, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
}
func testThatStringResponseSerializerSucceedsWithUTF8DataAndUTF8ProvidedEncoding() {
let serializer = Request.stringResponseSerializer(encoding: NSUTF8StringEncoding)
let data = "data".dataUsingEncoding(NSUTF8StringEncoding)!
// When
let result = serializer.serializeResponse(nil, nil, data, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
}
func testThatStringResponseSerializerSucceedsWithUTF8DataUsingResponseTextEncodingName() {
let serializer = Request.stringResponseSerializer()
let data = "data".dataUsingEncoding(NSUTF8StringEncoding)!
let response = NSHTTPURLResponse(
URL: NSURL(string: "https://httpbin.org/get")!,
statusCode: 200,
HTTPVersion: "HTTP/1.1",
headerFields: ["Content-Type": "image/jpeg; charset=utf-8"]
)
// When
let result = serializer.serializeResponse(nil, response, data, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
}
func testThatStringResponseSerializerFailsWithUTF32DataAndUTF8ProvidedEncoding() {
// Given
let serializer = Request.stringResponseSerializer(encoding: NSUTF8StringEncoding)
let data = "random data".dataUsingEncoding(NSUTF32StringEncoding)!
// When
let result = serializer.serializeResponse(nil, nil, data, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.StringSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatStringResponseSerializerFailsWithUTF32DataAndUTF8ResponseEncoding() {
// Given
let serializer = Request.stringResponseSerializer()
let data = "random data".dataUsingEncoding(NSUTF32StringEncoding)!
let response = NSHTTPURLResponse(
URL: NSURL(string: "https://httpbin.org/get")!,
statusCode: 200,
HTTPVersion: "HTTP/1.1",
headerFields: ["Content-Type": "image/jpeg; charset=utf-8"]
)
// When
let result = serializer.serializeResponse(nil, response, data, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.StringSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatStringResponseSerializerFailsWhenErrorIsNotNil() {
// Given
let serializer = Request.stringResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, nil, error)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, self.error.code, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatStringResponseSerializerFailsWhenDataIsNilWithNon204ResponseStatusCode() {
// Given
let serializer = Request.stringResponseSerializer()
let URL = NSURL(string: "https://httpbin.org/get")!
let response = NSHTTPURLResponse(URL: URL, statusCode: 200, HTTPVersion: "HTTP/1.1", headerFields: nil)
// When
let result = serializer.serializeResponse(nil, response, nil, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.StringSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatStringResponseSerializerSucceedsWhenDataIsNilWith204ResponseStatusCode() {
// Given
let serializer = Request.stringResponseSerializer()
let URL = NSURL(string: "https://httpbin.org/get")!
let response = NSHTTPURLResponse(URL: URL, statusCode: 204, HTTPVersion: "HTTP/1.1", headerFields: nil)
// When
let result = serializer.serializeResponse(nil, response, nil, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
if let string = result.value {
XCTAssertEqual(string, "", "string should be equal to empty string")
}
}
// MARK: - JSON Response Serializer Tests
func testThatJSONResponseSerializerFailsWhenDataIsNil() {
// Given
let serializer = Request.JSONResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, nil, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.JSONSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatJSONResponseSerializerFailsWhenDataIsEmpty() {
// Given
let serializer = Request.JSONResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, NSData(), nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.JSONSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatJSONResponseSerializerSucceedsWhenDataIsValidJSON() {
// Given
let serializer = Request.stringResponseSerializer()
let data = "{\"json\": true}".dataUsingEncoding(NSUTF8StringEncoding)!
// When
let result = serializer.serializeResponse(nil, nil, data, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
}
func testThatJSONResponseSerializerFailsWhenDataIsInvalidJSON() {
// Given
let serializer = Request.JSONResponseSerializer()
let data = "definitely not valid json".dataUsingEncoding(NSUTF8StringEncoding)!
// When
let result = serializer.serializeResponse(nil, nil, data, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, NSCocoaErrorDomain, "error domain should match expected value")
XCTAssertEqual(error.code, 3840, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatJSONResponseSerializerFailsWhenErrorIsNotNil() {
// Given
let serializer = Request.JSONResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, nil, error)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, self.error.code, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatJSONResponseSerializerFailsWhenDataIsNilWithNon204ResponseStatusCode() {
// Given
let serializer = Request.JSONResponseSerializer()
let URL = NSURL(string: "https://httpbin.org/get")!
let response = NSHTTPURLResponse(URL: URL, statusCode: 200, HTTPVersion: "HTTP/1.1", headerFields: nil)
// When
let result = serializer.serializeResponse(nil, response, nil, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.JSONSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatJSONResponseSerializerSucceedsWhenDataIsNilWith204ResponseStatusCode() {
// Given
let serializer = Request.JSONResponseSerializer()
let URL = NSURL(string: "https://httpbin.org/get")!
let response = NSHTTPURLResponse(URL: URL, statusCode: 204, HTTPVersion: "HTTP/1.1", headerFields: nil)
// When
let result = serializer.serializeResponse(nil, response, nil, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
if let json = result.value as? NSNull {
XCTAssertEqual(json, NSNull(), "json should be equal to NSNull")
}
}
// MARK: - Property List Response Serializer Tests
func testThatPropertyListResponseSerializerFailsWhenDataIsNil() {
// Given
let serializer = Request.propertyListResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, nil, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.PropertyListSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatPropertyListResponseSerializerFailsWhenDataIsEmpty() {
// Given
let serializer = Request.propertyListResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, NSData(), nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.PropertyListSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatPropertyListResponseSerializerSucceedsWhenDataIsValidPropertyListData() {
// Given
let serializer = Request.propertyListResponseSerializer()
let data = NSKeyedArchiver.archivedDataWithRootObject(["foo": "bar"])
// When
let result = serializer.serializeResponse(nil, nil, data, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
}
func testThatPropertyListResponseSerializerFailsWhenDataIsInvalidPropertyListData() {
// Given
let serializer = Request.propertyListResponseSerializer()
let data = "definitely not valid plist data".dataUsingEncoding(NSUTF8StringEncoding)!
// When
let result = serializer.serializeResponse(nil, nil, data, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, NSCocoaErrorDomain, "error domain should match expected value")
XCTAssertEqual(error.code, 3840, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatPropertyListResponseSerializerFailsWhenErrorIsNotNil() {
// Given
let serializer = Request.propertyListResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, nil, error)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, self.error.code, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatPropertyListResponseSerializerFailsWhenDataIsNilWithNon204ResponseStatusCode() {
// Given
let serializer = Request.propertyListResponseSerializer()
let URL = NSURL(string: "https://httpbin.org/get")!
let response = NSHTTPURLResponse(URL: URL, statusCode: 200, HTTPVersion: "HTTP/1.1", headerFields: nil)
// When
let result = serializer.serializeResponse(nil, response, nil, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.PropertyListSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatPropertyListResponseSerializerSucceedsWhenDataIsNilWith204ResponseStatusCode() {
// Given
let serializer = Request.propertyListResponseSerializer()
let URL = NSURL(string: "https://httpbin.org/get")!
let response = NSHTTPURLResponse(URL: URL, statusCode: 204, HTTPVersion: "HTTP/1.1", headerFields: nil)
// When
let result = serializer.serializeResponse(nil, response, nil, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
if let plist = result.value as? NSNull {
XCTAssertEqual(plist, NSNull(), "plist should be equal to NSNull")
}
}
}
| @@ -266,8 +348,8 @@ class ResponseSerializationTestCase: BaseTestCase {
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
- XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
- XCTAssertEqual(error.code, Error.Code.JSONSerializationFailed.rawValue, "error code should match expected value")
+ XCTAssertEqual(error.domain, NSCocoaErrorDomain, "error domain should match expected value")
+ XCTAssertEqual(error.code, 3840, "error code should match expected value") | Tests/ResponseSerializationTests.swift | 0 | Swift | 0.643 | bug | 113 | 592 | 592 | false | Feature - Added 204 Support to Response Serializers | 889 | Alamofire/Alamofire | 41,690 | Swift | kylef | cnoon |
// ResponseSerializationTests.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Alamofire
import Foundation
import XCTest
class ResponseSerializationTestCase: BaseTestCase {
let error = NSError(domain: Error.Domain, code: -10000, userInfo: nil)
// MARK: - Data Response Serializer Tests
func testThatDataResponseSerializerSucceedsWhenDataIsNotNil() {
// Given
let serializer = Request.dataResponseSerializer()
let data = "data".dataUsingEncoding(NSUTF8StringEncoding)!
// When
let result = serializer.serializeResponse(nil, nil, data, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
}
func testThatDataResponseSerializerFailsWhenDataIsNil() {
// Given
let serializer = Request.dataResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, nil, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.DataSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatDataResponseSerializerFailsWhenErrorIsNotNil() {
// Given
let serializer = Request.dataResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, nil, error)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, self.error.code, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatDataResponseSerializerFailsWhenDataIsNilWithNon204ResponseStatusCode() {
// Given
let serializer = Request.dataResponseSerializer()
let URL = NSURL(string: "https://httpbin.org/get")!
let response = NSHTTPURLResponse(URL: URL, statusCode: 200, HTTPVersion: "HTTP/1.1", headerFields: nil)
// When
let result = serializer.serializeResponse(nil, response, nil, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.DataSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatDataResponseSerializerSucceedsWhenDataIsNilWith204ResponseStatusCode() {
// Given
let serializer = Request.dataResponseSerializer()
let URL = NSURL(string: "https://httpbin.org/get")!
let response = NSHTTPURLResponse(URL: URL, statusCode: 204, HTTPVersion: "HTTP/1.1", headerFields: nil)
// When
let result = serializer.serializeResponse(nil, response, nil, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
if let data = result.value {
XCTAssertEqual(data.length, 0, "data length should be zero")
}
}
// MARK: - String Response Serializer Tests
func testThatStringResponseSerializerFailsWhenDataIsNil() {
// Given
let serializer = Request.stringResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, nil, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.StringSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatStringResponseSerializerSucceedsWhenDataIsEmpty() {
// Given
let serializer = Request.stringResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, NSData(), nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
}
func testThatStringResponseSerializerSucceedsWithUTF8DataAndNoProvidedEncoding() {
let serializer = Request.stringResponseSerializer()
let data = "data".dataUsingEncoding(NSUTF8StringEncoding)!
// When
let result = serializer.serializeResponse(nil, nil, data, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
}
func testThatStringResponseSerializerSucceedsWithUTF8DataAndUTF8ProvidedEncoding() {
let serializer = Request.stringResponseSerializer(encoding: NSUTF8StringEncoding)
let data = "data".dataUsingEncoding(NSUTF8StringEncoding)!
// When
let result = serializer.serializeResponse(nil, nil, data, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
}
func testThatStringResponseSerializerSucceedsWithUTF8DataUsingResponseTextEncodingName() {
let serializer = Request.stringResponseSerializer()
let data = "data".dataUsingEncoding(NSUTF8StringEncoding)!
let response = NSHTTPURLResponse(
URL: NSURL(string: "https://httpbin.org/get")!,
statusCode: 200,
HTTPVersion: "HTTP/1.1",
headerFields: ["Content-Type": "image/jpeg; charset=utf-8"]
)
// When
let result = serializer.serializeResponse(nil, response, data, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
}
func testThatStringResponseSerializerFailsWithUTF32DataAndUTF8ProvidedEncoding() {
// Given
let serializer = Request.stringResponseSerializer(encoding: NSUTF8StringEncoding)
let data = "random data".dataUsingEncoding(NSUTF32StringEncoding)!
// When
let result = serializer.serializeResponse(nil, nil, data, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.StringSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatStringResponseSerializerFailsWithUTF32DataAndUTF8ResponseEncoding() {
// Given
let serializer = Request.stringResponseSerializer()
let data = "random data".dataUsingEncoding(NSUTF32StringEncoding)!
let response = NSHTTPURLResponse(
URL: NSURL(string: "https://httpbin.org/get")!,
statusCode: 200,
HTTPVersion: "HTTP/1.1",
headerFields: ["Content-Type": "image/jpeg; charset=utf-8"]
)
// When
let result = serializer.serializeResponse(nil, response, data, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.StringSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatStringResponseSerializerFailsWhenErrorIsNotNil() {
// Given
let serializer = Request.stringResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, nil, error)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, self.error.code, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatStringResponseSerializerFailsWhenDataIsNilWithNon204ResponseStatusCode() {
// Given
let serializer = Request.stringResponseSerializer()
let URL = NSURL(string: "https://httpbin.org/get")!
let response = NSHTTPURLResponse(URL: URL, statusCode: 200, HTTPVersion: "HTTP/1.1", headerFields: nil)
// When
let result = serializer.serializeResponse(nil, response, nil, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.StringSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatStringResponseSerializerSucceedsWhenDataIsNilWith204ResponseStatusCode() {
// Given
let serializer = Request.stringResponseSerializer()
let URL = NSURL(string: "https://httpbin.org/get")!
let response = NSHTTPURLResponse(URL: URL, statusCode: 204, HTTPVersion: "HTTP/1.1", headerFields: nil)
// When
let result = serializer.serializeResponse(nil, response, nil, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
if let string = result.value {
XCTAssertEqual(string, "", "string should be equal to empty string")
}
}
// MARK: - JSON Response Serializer Tests
func testThatJSONResponseSerializerFailsWhenDataIsNil() {
// Given
let serializer = Request.JSONResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, nil, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.JSONSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatJSONResponseSerializerFailsWhenDataIsEmpty() {
// Given
let serializer = Request.JSONResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, NSData(), nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, NSCocoaErrorDomain, "error domain should match expected value")
XCTAssertEqual(error.code, 3840, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatJSONResponseSerializerSucceedsWhenDataIsValidJSON() {
// Given
let serializer = Request.stringResponseSerializer()
let data = "{\"json\": true}".dataUsingEncoding(NSUTF8StringEncoding)!
// When
let result = serializer.serializeResponse(nil, nil, data, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
}
func testThatJSONResponseSerializerFailsWhenDataIsInvalidJSON() {
// Given
let serializer = Request.JSONResponseSerializer()
let data = "definitely not valid json".dataUsingEncoding(NSUTF8StringEncoding)!
// When
let result = serializer.serializeResponse(nil, nil, data, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, NSCocoaErrorDomain, "error domain should match expected value")
XCTAssertEqual(error.code, 3840, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatJSONResponseSerializerFailsWhenErrorIsNotNil() {
// Given
let serializer = Request.JSONResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, nil, error)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, self.error.code, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatJSONResponseSerializerFailsWhenDataIsNilWithNon204ResponseStatusCode() {
// Given
let serializer = Request.JSONResponseSerializer()
let URL = NSURL(string: "https://httpbin.org/get")!
let response = NSHTTPURLResponse(URL: URL, statusCode: 200, HTTPVersion: "HTTP/1.1", headerFields: nil)
// When
let result = serializer.serializeResponse(nil, response, nil, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.JSONSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatJSONResponseSerializerSucceedsWhenDataIsNilWith204ResponseStatusCode() {
// Given
let serializer = Request.JSONResponseSerializer()
let URL = NSURL(string: "https://httpbin.org/get")!
let response = NSHTTPURLResponse(URL: URL, statusCode: 204, HTTPVersion: "HTTP/1.1", headerFields: nil)
// When
let result = serializer.serializeResponse(nil, response, nil, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
if let json = result.value as? NSNull {
XCTAssertEqual(json, NSNull(), "json should be equal to NSNull")
}
}
// MARK: - Property List Response Serializer Tests
func testThatPropertyListResponseSerializerFailsWhenDataIsNil() {
// Given
let serializer = Request.propertyListResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, nil, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.PropertyListSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatPropertyListResponseSerializerFailsWhenDataIsEmpty() {
// Given
let serializer = Request.propertyListResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, NSData(), nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, NSCocoaErrorDomain, "error domain should match expected value")
XCTAssertEqual(error.code, 3840, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatPropertyListResponseSerializerSucceedsWhenDataIsValidPropertyListData() {
// Given
let serializer = Request.propertyListResponseSerializer()
let data = NSKeyedArchiver.archivedDataWithRootObject(["foo": "bar"])
// When
let result = serializer.serializeResponse(nil, nil, data, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
}
func testThatPropertyListResponseSerializerFailsWhenDataIsInvalidPropertyListData() {
// Given
let serializer = Request.propertyListResponseSerializer()
let data = "definitely not valid plist data".dataUsingEncoding(NSUTF8StringEncoding)!
// When
let result = serializer.serializeResponse(nil, nil, data, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, NSCocoaErrorDomain, "error domain should match expected value")
XCTAssertEqual(error.code, 3840, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatPropertyListResponseSerializerFailsWhenErrorIsNotNil() {
// Given
let serializer = Request.propertyListResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, nil, error)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, self.error.code, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatPropertyListResponseSerializerFailsWhenDataIsNilWithNon204ResponseStatusCode() {
// Given
let serializer = Request.propertyListResponseSerializer()
let URL = NSURL(string: "https://httpbin.org/get")!
let response = NSHTTPURLResponse(URL: URL, statusCode: 200, HTTPVersion: "HTTP/1.1", headerFields: nil)
// When
let result = serializer.serializeResponse(nil, response, nil, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.PropertyListSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatPropertyListResponseSerializerSucceedsWhenDataIsNilWith204ResponseStatusCode() {
// Given
let serializer = Request.propertyListResponseSerializer()
let URL = NSURL(string: "https://httpbin.org/get")!
let response = NSHTTPURLResponse(URL: URL, statusCode: 204, HTTPVersion: "HTTP/1.1", headerFields: nil)
// When
let result = serializer.serializeResponse(nil, response, nil, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
if let plist = result.value as? NSNull {
XCTAssertEqual(plist, NSNull(), "plist should be equal to NSNull")
}
}
}
| Yeah it definitely is an `NSPropertyListReadCorruptError`. Looks like they used the same errors for JSON as they did plists rather than redefining special error codes for JSON. With that said, should we keep the `data.length > 0` check to instead through an actual Alamofire JSON error instead? I think it would make sense in both JSON and plist cases to keep that check. Thoughts?
| // ResponseSerializationTests.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Alamofire
import Foundation
import XCTest
class ResponseSerializationTestCase: BaseTestCase {
let error = NSError(domain: Error.Domain, code: -10000, userInfo: nil)
// MARK: - Data Response Serializer Tests
func testThatDataResponseSerializerSucceedsWhenDataIsNotNil() {
// Given
let serializer = Request.dataResponseSerializer()
let data = "data".dataUsingEncoding(NSUTF8StringEncoding)!
// When
let result = serializer.serializeResponse(nil, nil, data, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
}
func testThatDataResponseSerializerFailsWhenDataIsNil() {
// Given
let serializer = Request.dataResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, nil, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.DataSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatDataResponseSerializerFailsWhenErrorIsNotNil() {
// Given
let serializer = Request.dataResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, nil, error)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, self.error.code, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatDataResponseSerializerFailsWhenDataIsNilWithNon204ResponseStatusCode() {
// Given
let serializer = Request.dataResponseSerializer()
let URL = NSURL(string: "https://httpbin.org/get")!
let response = NSHTTPURLResponse(URL: URL, statusCode: 200, HTTPVersion: "HTTP/1.1", headerFields: nil)
// When
let result = serializer.serializeResponse(nil, response, nil, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.DataSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatDataResponseSerializerSucceedsWhenDataIsNilWith204ResponseStatusCode() {
// Given
let serializer = Request.dataResponseSerializer()
let URL = NSURL(string: "https://httpbin.org/get")!
let response = NSHTTPURLResponse(URL: URL, statusCode: 204, HTTPVersion: "HTTP/1.1", headerFields: nil)
// When
let result = serializer.serializeResponse(nil, response, nil, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
if let data = result.value {
XCTAssertEqual(data.length, 0, "data length should be zero")
}
}
// MARK: - String Response Serializer Tests
func testThatStringResponseSerializerFailsWhenDataIsNil() {
// Given
let serializer = Request.stringResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, nil, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.StringSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatStringResponseSerializerSucceedsWhenDataIsEmpty() {
// Given
let serializer = Request.stringResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, NSData(), nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
}
func testThatStringResponseSerializerSucceedsWithUTF8DataAndNoProvidedEncoding() {
let serializer = Request.stringResponseSerializer()
let data = "data".dataUsingEncoding(NSUTF8StringEncoding)!
// When
let result = serializer.serializeResponse(nil, nil, data, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
}
func testThatStringResponseSerializerSucceedsWithUTF8DataAndUTF8ProvidedEncoding() {
let serializer = Request.stringResponseSerializer(encoding: NSUTF8StringEncoding)
let data = "data".dataUsingEncoding(NSUTF8StringEncoding)!
// When
let result = serializer.serializeResponse(nil, nil, data, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
}
func testThatStringResponseSerializerSucceedsWithUTF8DataUsingResponseTextEncodingName() {
let serializer = Request.stringResponseSerializer()
let data = "data".dataUsingEncoding(NSUTF8StringEncoding)!
let response = NSHTTPURLResponse(
URL: NSURL(string: "https://httpbin.org/get")!,
statusCode: 200,
HTTPVersion: "HTTP/1.1",
headerFields: ["Content-Type": "image/jpeg; charset=utf-8"]
)
// When
let result = serializer.serializeResponse(nil, response, data, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
}
func testThatStringResponseSerializerFailsWithUTF32DataAndUTF8ProvidedEncoding() {
// Given
let serializer = Request.stringResponseSerializer(encoding: NSUTF8StringEncoding)
let data = "random data".dataUsingEncoding(NSUTF32StringEncoding)!
// When
let result = serializer.serializeResponse(nil, nil, data, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.StringSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatStringResponseSerializerFailsWithUTF32DataAndUTF8ResponseEncoding() {
// Given
let serializer = Request.stringResponseSerializer()
let data = "random data".dataUsingEncoding(NSUTF32StringEncoding)!
let response = NSHTTPURLResponse(
URL: NSURL(string: "https://httpbin.org/get")!,
statusCode: 200,
HTTPVersion: "HTTP/1.1",
headerFields: ["Content-Type": "image/jpeg; charset=utf-8"]
)
// When
let result = serializer.serializeResponse(nil, response, data, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.StringSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatStringResponseSerializerFailsWhenErrorIsNotNil() {
// Given
let serializer = Request.stringResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, nil, error)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, self.error.code, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatStringResponseSerializerFailsWhenDataIsNilWithNon204ResponseStatusCode() {
// Given
let serializer = Request.stringResponseSerializer()
let URL = NSURL(string: "https://httpbin.org/get")!
let response = NSHTTPURLResponse(URL: URL, statusCode: 200, HTTPVersion: "HTTP/1.1", headerFields: nil)
// When
let result = serializer.serializeResponse(nil, response, nil, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.StringSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatStringResponseSerializerSucceedsWhenDataIsNilWith204ResponseStatusCode() {
// Given
let serializer = Request.stringResponseSerializer()
let URL = NSURL(string: "https://httpbin.org/get")!
let response = NSHTTPURLResponse(URL: URL, statusCode: 204, HTTPVersion: "HTTP/1.1", headerFields: nil)
// When
let result = serializer.serializeResponse(nil, response, nil, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
if let string = result.value {
XCTAssertEqual(string, "", "string should be equal to empty string")
}
}
// MARK: - JSON Response Serializer Tests
func testThatJSONResponseSerializerFailsWhenDataIsNil() {
// Given
let serializer = Request.JSONResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, nil, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.JSONSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatJSONResponseSerializerFailsWhenDataIsEmpty() {
// Given
let serializer = Request.JSONResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, NSData(), nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.JSONSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatJSONResponseSerializerSucceedsWhenDataIsValidJSON() {
// Given
let serializer = Request.stringResponseSerializer()
let data = "{\"json\": true}".dataUsingEncoding(NSUTF8StringEncoding)!
// When
let result = serializer.serializeResponse(nil, nil, data, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
}
func testThatJSONResponseSerializerFailsWhenDataIsInvalidJSON() {
// Given
let serializer = Request.JSONResponseSerializer()
let data = "definitely not valid json".dataUsingEncoding(NSUTF8StringEncoding)!
// When
let result = serializer.serializeResponse(nil, nil, data, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, NSCocoaErrorDomain, "error domain should match expected value")
XCTAssertEqual(error.code, 3840, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatJSONResponseSerializerFailsWhenErrorIsNotNil() {
// Given
let serializer = Request.JSONResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, nil, error)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, self.error.code, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatJSONResponseSerializerFailsWhenDataIsNilWithNon204ResponseStatusCode() {
// Given
let serializer = Request.JSONResponseSerializer()
let URL = NSURL(string: "https://httpbin.org/get")!
let response = NSHTTPURLResponse(URL: URL, statusCode: 200, HTTPVersion: "HTTP/1.1", headerFields: nil)
// When
let result = serializer.serializeResponse(nil, response, nil, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.JSONSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatJSONResponseSerializerSucceedsWhenDataIsNilWith204ResponseStatusCode() {
// Given
let serializer = Request.JSONResponseSerializer()
let URL = NSURL(string: "https://httpbin.org/get")!
let response = NSHTTPURLResponse(URL: URL, statusCode: 204, HTTPVersion: "HTTP/1.1", headerFields: nil)
// When
let result = serializer.serializeResponse(nil, response, nil, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
if let json = result.value as? NSNull {
XCTAssertEqual(json, NSNull(), "json should be equal to NSNull")
}
}
// MARK: - Property List Response Serializer Tests
func testThatPropertyListResponseSerializerFailsWhenDataIsNil() {
// Given
let serializer = Request.propertyListResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, nil, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.PropertyListSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatPropertyListResponseSerializerFailsWhenDataIsEmpty() {
// Given
let serializer = Request.propertyListResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, NSData(), nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.PropertyListSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatPropertyListResponseSerializerSucceedsWhenDataIsValidPropertyListData() {
// Given
let serializer = Request.propertyListResponseSerializer()
let data = NSKeyedArchiver.archivedDataWithRootObject(["foo": "bar"])
// When
let result = serializer.serializeResponse(nil, nil, data, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
}
func testThatPropertyListResponseSerializerFailsWhenDataIsInvalidPropertyListData() {
// Given
let serializer = Request.propertyListResponseSerializer()
let data = "definitely not valid plist data".dataUsingEncoding(NSUTF8StringEncoding)!
// When
let result = serializer.serializeResponse(nil, nil, data, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, NSCocoaErrorDomain, "error domain should match expected value")
XCTAssertEqual(error.code, 3840, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatPropertyListResponseSerializerFailsWhenErrorIsNotNil() {
// Given
let serializer = Request.propertyListResponseSerializer()
// When
let result = serializer.serializeResponse(nil, nil, nil, error)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, self.error.code, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatPropertyListResponseSerializerFailsWhenDataIsNilWithNon204ResponseStatusCode() {
// Given
let serializer = Request.propertyListResponseSerializer()
let URL = NSURL(string: "https://httpbin.org/get")!
let response = NSHTTPURLResponse(URL: URL, statusCode: 200, HTTPVersion: "HTTP/1.1", headerFields: nil)
// When
let result = serializer.serializeResponse(nil, response, nil, nil)
// Then
XCTAssertTrue(result.isFailure, "result is failure should be true")
XCTAssertNil(result.value, "result value should be nil")
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
XCTAssertEqual(error.code, Error.Code.PropertyListSerializationFailed.rawValue, "error code should match expected value")
} else {
XCTFail("error should not be nil")
}
}
func testThatPropertyListResponseSerializerSucceedsWhenDataIsNilWith204ResponseStatusCode() {
// Given
let serializer = Request.propertyListResponseSerializer()
let URL = NSURL(string: "https://httpbin.org/get")!
let response = NSHTTPURLResponse(URL: URL, statusCode: 204, HTTPVersion: "HTTP/1.1", headerFields: nil)
// When
let result = serializer.serializeResponse(nil, response, nil, nil)
// Then
XCTAssertTrue(result.isSuccess, "result is success should be true")
XCTAssertNotNil(result.value, "result value should not be nil")
XCTAssertNil(result.error, "result error should be nil")
if let plist = result.value as? NSNull {
XCTAssertEqual(plist, NSNull(), "plist should be equal to NSNull")
}
}
}
| @@ -266,8 +348,8 @@ class ResponseSerializationTestCase: BaseTestCase {
XCTAssertNotNil(result.error, "result error should not be nil")
if let error = result.error {
- XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value")
- XCTAssertEqual(error.code, Error.Code.JSONSerializationFailed.rawValue, "error code should match expected value")
+ XCTAssertEqual(error.domain, NSCocoaErrorDomain, "error domain should match expected value")
+ XCTAssertEqual(error.code, 3840, "error code should match expected value") | Tests/ResponseSerializationTests.swift | 0 | Swift | 0.786 | question | 382 | 592 | 592 | false | Feature - Added 204 Support to Response Serializers | 889 | Alamofire/Alamofire | 41,690 | Swift | cnoon | cnoon |
// ResponseSerialization.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
// MARK: ResponseSerializer
/**
The type in which all response serializers must conform to in order to serialize a response.
*/
public protocol ResponseSerializerType {
/// The type of serialized object to be created by this `ResponseSerializerType`.
typealias SerializedObject
/// The type of error to be created by this `ResponseSerializer` if serialization fails.
typealias ErrorObject: ErrorType
/**
A closure used by response handlers that takes a request, response, data and error and returns a result.
*/
var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result<SerializedObject, ErrorObject> { get }
}
// MARK: -
/**
A generic `ResponseSerializerType` used to serialize a request, response, and data into a serialized object.
*/
public struct ResponseSerializer<Value, Error: ErrorType>: ResponseSerializerType {
/// The type of serialized object to be created by this `ResponseSerializer`.
public typealias SerializedObject = Value
/// The type of error to be created by this `ResponseSerializer` if serialization fails.
public typealias ErrorObject = Error
/**
A closure used by response handlers that takes a request, response, data and error and returns a result.
*/
public var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result<Value, Error>
/**
Initializes the `ResponseSerializer` instance with the given serialize response closure.
- parameter serializeResponse: The closure used to serialize the response.
- returns: The new generic response serializer instance.
*/
public init(serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result<Value, Error>) {
self.serializeResponse = serializeResponse
}
}
// MARK: - Default
extension Request {
/**
Adds a handler to be called once the request has finished.
- parameter queue: The queue on which the completion handler is dispatched.
- parameter completionHandler: The code to be executed once the request has finished.
- returns: The request.
*/
public func response(
queue queue: dispatch_queue_t? = nil,
completionHandler: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Void)
-> Self
{
delegate.queue.addOperationWithBlock {
dispatch_async(queue ?? dispatch_get_main_queue()) {
completionHandler(self.request, self.response, self.delegate.data, self.delegate.error)
}
}
return self
}
/**
Adds a handler to be called once the request has finished.
- parameter queue: The queue on which the completion handler is dispatched.
- parameter responseSerializer: The response serializer responsible for serializing the request, response,
and data.
- parameter completionHandler: The code to be executed once the request has finished.
- returns: The request.
*/
public func response<T: ResponseSerializerType>(
queue queue: dispatch_queue_t? = nil,
responseSerializer: T,
completionHandler: Response<T.SerializedObject, T.ErrorObject> -> Void)
-> Self
{
delegate.queue.addOperationWithBlock {
let result = responseSerializer.serializeResponse(
self.request,
self.response,
self.delegate.data,
self.delegate.error
)
dispatch_async(queue ?? dispatch_get_main_queue()) {
let response = Response<T.SerializedObject, T.ErrorObject>(
request: self.request,
response: self.response,
data: self.delegate.data,
result: result
)
completionHandler(response)
}
}
return self
}
}
// MARK: - Data
extension Request {
/**
Creates a response serializer that returns the associated data as-is.
- returns: A data response serializer.
*/
public static func dataResponseSerializer() -> ResponseSerializer<NSData, NSError> {
return ResponseSerializer { _, response, data, error in
guard error == nil else { return .Failure(error!) }
guard response?.statusCode ?? -1 != 204 else { return .Success(NSData()) }
guard let validData = data else {
let failureReason = "Data could not be serialized. Input data was nil."
let error = Error.errorWithCode(.DataSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
return .Success(validData)
}
}
/**
Adds a handler to be called once the request has finished.
- parameter completionHandler: The code to be executed once the request has finished.
- returns: The request.
*/
public func responseData(completionHandler: Response<NSData, NSError> -> Void) -> Self {
return response(responseSerializer: Request.dataResponseSerializer(), completionHandler: completionHandler)
}
}
// MARK: - String
extension Request {
/**
Creates a response serializer that returns a string initialized from the response data with the specified
string encoding.
- parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server
response, falling back to the default HTTP default character set, ISO-8859-1.
- returns: A string response serializer.
*/
public static func stringResponseSerializer(
var encoding encoding: NSStringEncoding? = nil)
-> ResponseSerializer<String, NSError>
{
return ResponseSerializer { _, response, data, error in
guard error == nil else { return .Failure(error!) }
guard response?.statusCode ?? -1 != 204 else { return .Success("") }
guard let validData = data else {
let failureReason = "String could not be serialized. Input data was nil."
let error = Error.errorWithCode(.StringSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
if let encodingName = response?.textEncodingName where encoding == nil {
encoding = CFStringConvertEncodingToNSStringEncoding(
CFStringConvertIANACharSetNameToEncoding(encodingName)
)
}
let actualEncoding = encoding ?? NSISOLatin1StringEncoding
if let string = String(data: validData, encoding: actualEncoding) {
return .Success(string)
} else {
let failureReason = "String could not be serialized with encoding: \(actualEncoding)"
let error = Error.errorWithCode(.StringSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
}
}
/**
Adds a handler to be called once the request has finished.
- parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the
server response, falling back to the default HTTP default character set,
ISO-8859-1.
- parameter completionHandler: A closure to be executed once the request has finished.
- returns: The request.
*/
public func responseString(
encoding encoding: NSStringEncoding? = nil,
completionHandler: Response<String, NSError> -> Void)
-> Self
{
return response(
responseSerializer: Request.stringResponseSerializer(encoding: encoding),
completionHandler: completionHandler
)
}
}
// MARK: - JSON
extension Request {
/**
Creates a response serializer that returns a JSON object constructed from the response data using
`NSJSONSerialization` with the specified reading options.
- parameter options: The JSON serialization reading options. `.AllowFragments` by default.
- returns: A JSON object response serializer.
*/
public static func JSONResponseSerializer(
options options: NSJSONReadingOptions = .AllowFragments)
-> ResponseSerializer<AnyObject, NSError>
{
return ResponseSerializer { _, response, data, error in
guard error == nil else { return .Failure(error!) }
guard response?.statusCode ?? -1 != 204 else { return .Success(NSNull()) }
guard let validData = data else {
let failureReason = "JSON could not be serialized. Input data was nil."
let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
do {
let JSON = try NSJSONSerialization.JSONObjectWithData(validData, options: options)
return .Success(JSON)
} catch {
return .Failure(error as NSError)
}
}
}
/**
Adds a handler to be called once the request has finished.
- parameter options: The JSON serialization reading options. `.AllowFragments` by default.
- parameter completionHandler: A closure to be executed once the request has finished.
- returns: The request.
*/
public func responseJSON(
options options: NSJSONReadingOptions = .AllowFragments,
completionHandler: Response<AnyObject, NSError> -> Void)
-> Self
{
return response(
responseSerializer: Request.JSONResponseSerializer(options: options),
completionHandler: completionHandler
)
}
}
// MARK: - Property List
extension Request {
/**
Creates a response serializer that returns an object constructed from the response data using
`NSPropertyListSerialization` with the specified reading options.
- parameter options: The property list reading options. `NSPropertyListReadOptions()` by default.
- returns: A property list object response serializer.
*/
public static func propertyListResponseSerializer(
options options: NSPropertyListReadOptions = NSPropertyListReadOptions())
-> ResponseSerializer<AnyObject, NSError>
{
return ResponseSerializer { _, response, data, error in
guard error == nil else { return .Failure(error!) }
guard response?.statusCode ?? -1 != 204 else { return .Success(NSNull()) }
guard let validData = data else {
let failureReason = "Property list could not be serialized. Input data was nil."
let error = Error.errorWithCode(.PropertyListSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
do {
let plist = try NSPropertyListSerialization.propertyListWithData(validData, options: options, format: nil)
return .Success(plist)
} catch {
return .Failure(error as NSError)
}
}
}
/**
Adds a handler to be called once the request has finished.
- parameter options: The property list reading options. `0` by default.
- parameter completionHandler: A closure to be executed once the request has finished. The closure takes 3
arguments: the URL request, the URL response, the server data and the result
produced while creating the property list.
- returns: The request.
*/
public func responsePropertyList(
options options: NSPropertyListReadOptions = NSPropertyListReadOptions(),
completionHandler: Response<AnyObject, NSError> -> Void)
-> Self
{
return response(
responseSerializer: Request.propertyListResponseSerializer(options: options),
completionHandler: completionHandler
)
}
}
| How do you feel about:
``` swift
guard let response = response where response.statusCode != 204 else { return .Success(NSData()) }
```
It makes more sense to me than coalescing into a -1.
| // ResponseSerialization.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
// MARK: ResponseSerializer
/**
The type in which all response serializers must conform to in order to serialize a response.
*/
public protocol ResponseSerializerType {
/// The type of serialized object to be created by this `ResponseSerializerType`.
typealias SerializedObject
/// The type of error to be created by this `ResponseSerializer` if serialization fails.
typealias ErrorObject: ErrorType
/**
A closure used by response handlers that takes a request, response, data and error and returns a result.
*/
var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result<SerializedObject, ErrorObject> { get }
}
// MARK: -
/**
A generic `ResponseSerializerType` used to serialize a request, response, and data into a serialized object.
*/
public struct ResponseSerializer<Value, Error: ErrorType>: ResponseSerializerType {
/// The type of serialized object to be created by this `ResponseSerializer`.
public typealias SerializedObject = Value
/// The type of error to be created by this `ResponseSerializer` if serialization fails.
public typealias ErrorObject = Error
/**
A closure used by response handlers that takes a request, response, data and error and returns a result.
*/
public var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result<Value, Error>
/**
Initializes the `ResponseSerializer` instance with the given serialize response closure.
- parameter serializeResponse: The closure used to serialize the response.
- returns: The new generic response serializer instance.
*/
public init(serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result<Value, Error>) {
self.serializeResponse = serializeResponse
}
}
// MARK: - Default
extension Request {
/**
Adds a handler to be called once the request has finished.
- parameter queue: The queue on which the completion handler is dispatched.
- parameter completionHandler: The code to be executed once the request has finished.
- returns: The request.
*/
public func response(
queue queue: dispatch_queue_t? = nil,
completionHandler: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Void)
-> Self
{
delegate.queue.addOperationWithBlock {
dispatch_async(queue ?? dispatch_get_main_queue()) {
completionHandler(self.request, self.response, self.delegate.data, self.delegate.error)
}
}
return self
}
/**
Adds a handler to be called once the request has finished.
- parameter queue: The queue on which the completion handler is dispatched.
- parameter responseSerializer: The response serializer responsible for serializing the request, response,
and data.
- parameter completionHandler: The code to be executed once the request has finished.
- returns: The request.
*/
public func response<T: ResponseSerializerType>(
queue queue: dispatch_queue_t? = nil,
responseSerializer: T,
completionHandler: Response<T.SerializedObject, T.ErrorObject> -> Void)
-> Self
{
delegate.queue.addOperationWithBlock {
let result = responseSerializer.serializeResponse(
self.request,
self.response,
self.delegate.data,
self.delegate.error
)
dispatch_async(queue ?? dispatch_get_main_queue()) {
let response = Response<T.SerializedObject, T.ErrorObject>(
request: self.request,
response: self.response,
data: self.delegate.data,
result: result
)
completionHandler(response)
}
}
return self
}
}
// MARK: - Data
extension Request {
/**
Creates a response serializer that returns the associated data as-is.
- returns: A data response serializer.
*/
public static func dataResponseSerializer() -> ResponseSerializer<NSData, NSError> {
return ResponseSerializer { _, response, data, error in
guard error == nil else { return .Failure(error!) }
if let response = response where response.statusCode == 204 { return .Success(NSData()) }
guard let validData = data else {
let failureReason = "Data could not be serialized. Input data was nil."
let error = Error.errorWithCode(.DataSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
return .Success(validData)
}
}
/**
Adds a handler to be called once the request has finished.
- parameter completionHandler: The code to be executed once the request has finished.
- returns: The request.
*/
public func responseData(completionHandler: Response<NSData, NSError> -> Void) -> Self {
return response(responseSerializer: Request.dataResponseSerializer(), completionHandler: completionHandler)
}
}
// MARK: - String
extension Request {
/**
Creates a response serializer that returns a string initialized from the response data with the specified
string encoding.
- parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server
response, falling back to the default HTTP default character set, ISO-8859-1.
- returns: A string response serializer.
*/
public static func stringResponseSerializer(
var encoding encoding: NSStringEncoding? = nil)
-> ResponseSerializer<String, NSError>
{
return ResponseSerializer { _, response, data, error in
guard error == nil else { return .Failure(error!) }
if let response = response where response.statusCode == 204 { return .Success("") }
guard let validData = data else {
let failureReason = "String could not be serialized. Input data was nil."
let error = Error.errorWithCode(.StringSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
if let encodingName = response?.textEncodingName where encoding == nil {
encoding = CFStringConvertEncodingToNSStringEncoding(
CFStringConvertIANACharSetNameToEncoding(encodingName)
)
}
let actualEncoding = encoding ?? NSISOLatin1StringEncoding
if let string = String(data: validData, encoding: actualEncoding) {
return .Success(string)
} else {
let failureReason = "String could not be serialized with encoding: \(actualEncoding)"
let error = Error.errorWithCode(.StringSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
}
}
/**
Adds a handler to be called once the request has finished.
- parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the
server response, falling back to the default HTTP default character set,
ISO-8859-1.
- parameter completionHandler: A closure to be executed once the request has finished.
- returns: The request.
*/
public func responseString(
encoding encoding: NSStringEncoding? = nil,
completionHandler: Response<String, NSError> -> Void)
-> Self
{
return response(
responseSerializer: Request.stringResponseSerializer(encoding: encoding),
completionHandler: completionHandler
)
}
}
// MARK: - JSON
extension Request {
/**
Creates a response serializer that returns a JSON object constructed from the response data using
`NSJSONSerialization` with the specified reading options.
- parameter options: The JSON serialization reading options. `.AllowFragments` by default.
- returns: A JSON object response serializer.
*/
public static func JSONResponseSerializer(
options options: NSJSONReadingOptions = .AllowFragments)
-> ResponseSerializer<AnyObject, NSError>
{
return ResponseSerializer { _, response, data, error in
guard error == nil else { return .Failure(error!) }
if let response = response where response.statusCode == 204 { return .Success(NSNull()) }
guard let validData = data where validData.length > 0 else {
let failureReason = "JSON could not be serialized. Input data was nil or zero length."
let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
do {
let JSON = try NSJSONSerialization.JSONObjectWithData(validData, options: options)
return .Success(JSON)
} catch {
return .Failure(error as NSError)
}
}
}
/**
Adds a handler to be called once the request has finished.
- parameter options: The JSON serialization reading options. `.AllowFragments` by default.
- parameter completionHandler: A closure to be executed once the request has finished.
- returns: The request.
*/
public func responseJSON(
options options: NSJSONReadingOptions = .AllowFragments,
completionHandler: Response<AnyObject, NSError> -> Void)
-> Self
{
return response(
responseSerializer: Request.JSONResponseSerializer(options: options),
completionHandler: completionHandler
)
}
}
// MARK: - Property List
extension Request {
/**
Creates a response serializer that returns an object constructed from the response data using
`NSPropertyListSerialization` with the specified reading options.
- parameter options: The property list reading options. `NSPropertyListReadOptions()` by default.
- returns: A property list object response serializer.
*/
public static func propertyListResponseSerializer(
options options: NSPropertyListReadOptions = NSPropertyListReadOptions())
-> ResponseSerializer<AnyObject, NSError>
{
return ResponseSerializer { _, response, data, error in
guard error == nil else { return .Failure(error!) }
if let response = response where response.statusCode == 204 { return .Success(NSNull()) }
guard let validData = data where validData.length > 0 else {
let failureReason = "Property list could not be serialized. Input data was nil or zero length."
let error = Error.errorWithCode(.PropertyListSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
do {
let plist = try NSPropertyListSerialization.propertyListWithData(validData, options: options, format: nil)
return .Success(plist)
} catch {
return .Failure(error as NSError)
}
}
}
/**
Adds a handler to be called once the request has finished.
- parameter options: The property list reading options. `0` by default.
- parameter completionHandler: A closure to be executed once the request has finished. The closure takes 3
arguments: the URL request, the URL response, the server data and the result
produced while creating the property list.
- returns: The request.
*/
public func responsePropertyList(
options options: NSPropertyListReadOptions = NSPropertyListReadOptions(),
completionHandler: Response<AnyObject, NSError> -> Void)
-> Self
{
return response(
responseSerializer: Request.propertyListResponseSerializer(options: options),
completionHandler: completionHandler
)
}
}
| @@ -145,11 +145,13 @@ extension Request {
- returns: A data response serializer.
*/
public static func dataResponseSerializer() -> ResponseSerializer<NSData, NSError> {
- return ResponseSerializer { _, _, data, error in
+ return ResponseSerializer { _, response, data, error in
guard error == nil else { return .Failure(error!) }
- guard let validData = data where validData.length > 0 else {
- let failureReason = "Data could not be serialized. Input data was nil or zero length."
+ guard response?.statusCode ?? -1 != 204 else { return .Success(NSData()) } | Source/ResponseSerialization.swift | 0 | Swift | 0.714 | suggestion | 190 | 356 | 356 | false | Feature - Added 204 Support to Response Serializers | 889 | Alamofire/Alamofire | 41,690 | Swift | jshier | cnoon |
// ResponseSerialization.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
// MARK: ResponseSerializer
/**
The type in which all response serializers must conform to in order to serialize a response.
*/
public protocol ResponseSerializerType {
/// The type of serialized object to be created by this `ResponseSerializerType`.
typealias SerializedObject
/// The type of error to be created by this `ResponseSerializer` if serialization fails.
typealias ErrorObject: ErrorType
/**
A closure used by response handlers that takes a request, response, data and error and returns a result.
*/
var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result<SerializedObject, ErrorObject> { get }
}
// MARK: -
/**
A generic `ResponseSerializerType` used to serialize a request, response, and data into a serialized object.
*/
public struct ResponseSerializer<Value, Error: ErrorType>: ResponseSerializerType {
/// The type of serialized object to be created by this `ResponseSerializer`.
public typealias SerializedObject = Value
/// The type of error to be created by this `ResponseSerializer` if serialization fails.
public typealias ErrorObject = Error
/**
A closure used by response handlers that takes a request, response, data and error and returns a result.
*/
public var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result<Value, Error>
/**
Initializes the `ResponseSerializer` instance with the given serialize response closure.
- parameter serializeResponse: The closure used to serialize the response.
- returns: The new generic response serializer instance.
*/
public init(serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result<Value, Error>) {
self.serializeResponse = serializeResponse
}
}
// MARK: - Default
extension Request {
/**
Adds a handler to be called once the request has finished.
- parameter queue: The queue on which the completion handler is dispatched.
- parameter completionHandler: The code to be executed once the request has finished.
- returns: The request.
*/
public func response(
queue queue: dispatch_queue_t? = nil,
completionHandler: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Void)
-> Self
{
delegate.queue.addOperationWithBlock {
dispatch_async(queue ?? dispatch_get_main_queue()) {
completionHandler(self.request, self.response, self.delegate.data, self.delegate.error)
}
}
return self
}
/**
Adds a handler to be called once the request has finished.
- parameter queue: The queue on which the completion handler is dispatched.
- parameter responseSerializer: The response serializer responsible for serializing the request, response,
and data.
- parameter completionHandler: The code to be executed once the request has finished.
- returns: The request.
*/
public func response<T: ResponseSerializerType>(
queue queue: dispatch_queue_t? = nil,
responseSerializer: T,
completionHandler: Response<T.SerializedObject, T.ErrorObject> -> Void)
-> Self
{
delegate.queue.addOperationWithBlock {
let result = responseSerializer.serializeResponse(
self.request,
self.response,
self.delegate.data,
self.delegate.error
)
dispatch_async(queue ?? dispatch_get_main_queue()) {
let response = Response<T.SerializedObject, T.ErrorObject>(
request: self.request,
response: self.response,
data: self.delegate.data,
result: result
)
completionHandler(response)
}
}
return self
}
}
// MARK: - Data
extension Request {
/**
Creates a response serializer that returns the associated data as-is.
- returns: A data response serializer.
*/
public static func dataResponseSerializer() -> ResponseSerializer<NSData, NSError> {
return ResponseSerializer { _, response, data, error in
guard error == nil else { return .Failure(error!) }
guard response?.statusCode ?? -1 != 204 else { return .Success(NSData()) }
guard let validData = data else {
let failureReason = "Data could not be serialized. Input data was nil."
let error = Error.errorWithCode(.DataSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
return .Success(validData)
}
}
/**
Adds a handler to be called once the request has finished.
- parameter completionHandler: The code to be executed once the request has finished.
- returns: The request.
*/
public func responseData(completionHandler: Response<NSData, NSError> -> Void) -> Self {
return response(responseSerializer: Request.dataResponseSerializer(), completionHandler: completionHandler)
}
}
// MARK: - String
extension Request {
/**
Creates a response serializer that returns a string initialized from the response data with the specified
string encoding.
- parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server
response, falling back to the default HTTP default character set, ISO-8859-1.
- returns: A string response serializer.
*/
public static func stringResponseSerializer(
var encoding encoding: NSStringEncoding? = nil)
-> ResponseSerializer<String, NSError>
{
return ResponseSerializer { _, response, data, error in
guard error == nil else { return .Failure(error!) }
guard response?.statusCode ?? -1 != 204 else { return .Success("") }
guard let validData = data else {
let failureReason = "String could not be serialized. Input data was nil."
let error = Error.errorWithCode(.StringSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
if let encodingName = response?.textEncodingName where encoding == nil {
encoding = CFStringConvertEncodingToNSStringEncoding(
CFStringConvertIANACharSetNameToEncoding(encodingName)
)
}
let actualEncoding = encoding ?? NSISOLatin1StringEncoding
if let string = String(data: validData, encoding: actualEncoding) {
return .Success(string)
} else {
let failureReason = "String could not be serialized with encoding: \(actualEncoding)"
let error = Error.errorWithCode(.StringSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
}
}
/**
Adds a handler to be called once the request has finished.
- parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the
server response, falling back to the default HTTP default character set,
ISO-8859-1.
- parameter completionHandler: A closure to be executed once the request has finished.
- returns: The request.
*/
public func responseString(
encoding encoding: NSStringEncoding? = nil,
completionHandler: Response<String, NSError> -> Void)
-> Self
{
return response(
responseSerializer: Request.stringResponseSerializer(encoding: encoding),
completionHandler: completionHandler
)
}
}
// MARK: - JSON
extension Request {
/**
Creates a response serializer that returns a JSON object constructed from the response data using
`NSJSONSerialization` with the specified reading options.
- parameter options: The JSON serialization reading options. `.AllowFragments` by default.
- returns: A JSON object response serializer.
*/
public static func JSONResponseSerializer(
options options: NSJSONReadingOptions = .AllowFragments)
-> ResponseSerializer<AnyObject, NSError>
{
return ResponseSerializer { _, response, data, error in
guard error == nil else { return .Failure(error!) }
guard response?.statusCode ?? -1 != 204 else { return .Success(NSNull()) }
guard let validData = data else {
let failureReason = "JSON could not be serialized. Input data was nil."
let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
do {
let JSON = try NSJSONSerialization.JSONObjectWithData(validData, options: options)
return .Success(JSON)
} catch {
return .Failure(error as NSError)
}
}
}
/**
Adds a handler to be called once the request has finished.
- parameter options: The JSON serialization reading options. `.AllowFragments` by default.
- parameter completionHandler: A closure to be executed once the request has finished.
- returns: The request.
*/
public func responseJSON(
options options: NSJSONReadingOptions = .AllowFragments,
completionHandler: Response<AnyObject, NSError> -> Void)
-> Self
{
return response(
responseSerializer: Request.JSONResponseSerializer(options: options),
completionHandler: completionHandler
)
}
}
// MARK: - Property List
extension Request {
/**
Creates a response serializer that returns an object constructed from the response data using
`NSPropertyListSerialization` with the specified reading options.
- parameter options: The property list reading options. `NSPropertyListReadOptions()` by default.
- returns: A property list object response serializer.
*/
public static func propertyListResponseSerializer(
options options: NSPropertyListReadOptions = NSPropertyListReadOptions())
-> ResponseSerializer<AnyObject, NSError>
{
return ResponseSerializer { _, response, data, error in
guard error == nil else { return .Failure(error!) }
guard response?.statusCode ?? -1 != 204 else { return .Success(NSNull()) }
guard let validData = data else {
let failureReason = "Property list could not be serialized. Input data was nil."
let error = Error.errorWithCode(.PropertyListSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
do {
let plist = try NSPropertyListSerialization.propertyListWithData(validData, options: options, format: nil)
return .Success(plist)
} catch {
return .Failure(error as NSError)
}
}
}
/**
Adds a handler to be called once the request has finished.
- parameter options: The property list reading options. `0` by default.
- parameter completionHandler: A closure to be executed once the request has finished. The closure takes 3
arguments: the URL request, the URL response, the server data and the result
produced while creating the property list.
- returns: The request.
*/
public func responsePropertyList(
options options: NSPropertyListReadOptions = NSPropertyListReadOptions(),
completionHandler: Response<AnyObject, NSError> -> Void)
-> Self
{
return response(
responseSerializer: Request.propertyListResponseSerializer(options: options),
completionHandler: completionHandler
)
}
}
| Yup...make way more sense to me too! 😉🍻 Will change.
| // ResponseSerialization.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
// MARK: ResponseSerializer
/**
The type in which all response serializers must conform to in order to serialize a response.
*/
public protocol ResponseSerializerType {
/// The type of serialized object to be created by this `ResponseSerializerType`.
typealias SerializedObject
/// The type of error to be created by this `ResponseSerializer` if serialization fails.
typealias ErrorObject: ErrorType
/**
A closure used by response handlers that takes a request, response, data and error and returns a result.
*/
var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result<SerializedObject, ErrorObject> { get }
}
// MARK: -
/**
A generic `ResponseSerializerType` used to serialize a request, response, and data into a serialized object.
*/
public struct ResponseSerializer<Value, Error: ErrorType>: ResponseSerializerType {
/// The type of serialized object to be created by this `ResponseSerializer`.
public typealias SerializedObject = Value
/// The type of error to be created by this `ResponseSerializer` if serialization fails.
public typealias ErrorObject = Error
/**
A closure used by response handlers that takes a request, response, data and error and returns a result.
*/
public var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result<Value, Error>
/**
Initializes the `ResponseSerializer` instance with the given serialize response closure.
- parameter serializeResponse: The closure used to serialize the response.
- returns: The new generic response serializer instance.
*/
public init(serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result<Value, Error>) {
self.serializeResponse = serializeResponse
}
}
// MARK: - Default
extension Request {
/**
Adds a handler to be called once the request has finished.
- parameter queue: The queue on which the completion handler is dispatched.
- parameter completionHandler: The code to be executed once the request has finished.
- returns: The request.
*/
public func response(
queue queue: dispatch_queue_t? = nil,
completionHandler: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Void)
-> Self
{
delegate.queue.addOperationWithBlock {
dispatch_async(queue ?? dispatch_get_main_queue()) {
completionHandler(self.request, self.response, self.delegate.data, self.delegate.error)
}
}
return self
}
/**
Adds a handler to be called once the request has finished.
- parameter queue: The queue on which the completion handler is dispatched.
- parameter responseSerializer: The response serializer responsible for serializing the request, response,
and data.
- parameter completionHandler: The code to be executed once the request has finished.
- returns: The request.
*/
public func response<T: ResponseSerializerType>(
queue queue: dispatch_queue_t? = nil,
responseSerializer: T,
completionHandler: Response<T.SerializedObject, T.ErrorObject> -> Void)
-> Self
{
delegate.queue.addOperationWithBlock {
let result = responseSerializer.serializeResponse(
self.request,
self.response,
self.delegate.data,
self.delegate.error
)
dispatch_async(queue ?? dispatch_get_main_queue()) {
let response = Response<T.SerializedObject, T.ErrorObject>(
request: self.request,
response: self.response,
data: self.delegate.data,
result: result
)
completionHandler(response)
}
}
return self
}
}
// MARK: - Data
extension Request {
/**
Creates a response serializer that returns the associated data as-is.
- returns: A data response serializer.
*/
public static func dataResponseSerializer() -> ResponseSerializer<NSData, NSError> {
return ResponseSerializer { _, response, data, error in
guard error == nil else { return .Failure(error!) }
if let response = response where response.statusCode == 204 { return .Success(NSData()) }
guard let validData = data else {
let failureReason = "Data could not be serialized. Input data was nil."
let error = Error.errorWithCode(.DataSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
return .Success(validData)
}
}
/**
Adds a handler to be called once the request has finished.
- parameter completionHandler: The code to be executed once the request has finished.
- returns: The request.
*/
public func responseData(completionHandler: Response<NSData, NSError> -> Void) -> Self {
return response(responseSerializer: Request.dataResponseSerializer(), completionHandler: completionHandler)
}
}
// MARK: - String
extension Request {
/**
Creates a response serializer that returns a string initialized from the response data with the specified
string encoding.
- parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server
response, falling back to the default HTTP default character set, ISO-8859-1.
- returns: A string response serializer.
*/
public static func stringResponseSerializer(
var encoding encoding: NSStringEncoding? = nil)
-> ResponseSerializer<String, NSError>
{
return ResponseSerializer { _, response, data, error in
guard error == nil else { return .Failure(error!) }
if let response = response where response.statusCode == 204 { return .Success("") }
guard let validData = data else {
let failureReason = "String could not be serialized. Input data was nil."
let error = Error.errorWithCode(.StringSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
if let encodingName = response?.textEncodingName where encoding == nil {
encoding = CFStringConvertEncodingToNSStringEncoding(
CFStringConvertIANACharSetNameToEncoding(encodingName)
)
}
let actualEncoding = encoding ?? NSISOLatin1StringEncoding
if let string = String(data: validData, encoding: actualEncoding) {
return .Success(string)
} else {
let failureReason = "String could not be serialized with encoding: \(actualEncoding)"
let error = Error.errorWithCode(.StringSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
}
}
/**
Adds a handler to be called once the request has finished.
- parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the
server response, falling back to the default HTTP default character set,
ISO-8859-1.
- parameter completionHandler: A closure to be executed once the request has finished.
- returns: The request.
*/
public func responseString(
encoding encoding: NSStringEncoding? = nil,
completionHandler: Response<String, NSError> -> Void)
-> Self
{
return response(
responseSerializer: Request.stringResponseSerializer(encoding: encoding),
completionHandler: completionHandler
)
}
}
// MARK: - JSON
extension Request {
/**
Creates a response serializer that returns a JSON object constructed from the response data using
`NSJSONSerialization` with the specified reading options.
- parameter options: The JSON serialization reading options. `.AllowFragments` by default.
- returns: A JSON object response serializer.
*/
public static func JSONResponseSerializer(
options options: NSJSONReadingOptions = .AllowFragments)
-> ResponseSerializer<AnyObject, NSError>
{
return ResponseSerializer { _, response, data, error in
guard error == nil else { return .Failure(error!) }
if let response = response where response.statusCode == 204 { return .Success(NSNull()) }
guard let validData = data where validData.length > 0 else {
let failureReason = "JSON could not be serialized. Input data was nil or zero length."
let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
do {
let JSON = try NSJSONSerialization.JSONObjectWithData(validData, options: options)
return .Success(JSON)
} catch {
return .Failure(error as NSError)
}
}
}
/**
Adds a handler to be called once the request has finished.
- parameter options: The JSON serialization reading options. `.AllowFragments` by default.
- parameter completionHandler: A closure to be executed once the request has finished.
- returns: The request.
*/
public func responseJSON(
options options: NSJSONReadingOptions = .AllowFragments,
completionHandler: Response<AnyObject, NSError> -> Void)
-> Self
{
return response(
responseSerializer: Request.JSONResponseSerializer(options: options),
completionHandler: completionHandler
)
}
}
// MARK: - Property List
extension Request {
/**
Creates a response serializer that returns an object constructed from the response data using
`NSPropertyListSerialization` with the specified reading options.
- parameter options: The property list reading options. `NSPropertyListReadOptions()` by default.
- returns: A property list object response serializer.
*/
public static func propertyListResponseSerializer(
options options: NSPropertyListReadOptions = NSPropertyListReadOptions())
-> ResponseSerializer<AnyObject, NSError>
{
return ResponseSerializer { _, response, data, error in
guard error == nil else { return .Failure(error!) }
if let response = response where response.statusCode == 204 { return .Success(NSNull()) }
guard let validData = data where validData.length > 0 else {
let failureReason = "Property list could not be serialized. Input data was nil or zero length."
let error = Error.errorWithCode(.PropertyListSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
do {
let plist = try NSPropertyListSerialization.propertyListWithData(validData, options: options, format: nil)
return .Success(plist)
} catch {
return .Failure(error as NSError)
}
}
}
/**
Adds a handler to be called once the request has finished.
- parameter options: The property list reading options. `0` by default.
- parameter completionHandler: A closure to be executed once the request has finished. The closure takes 3
arguments: the URL request, the URL response, the server data and the result
produced while creating the property list.
- returns: The request.
*/
public func responsePropertyList(
options options: NSPropertyListReadOptions = NSPropertyListReadOptions(),
completionHandler: Response<AnyObject, NSError> -> Void)
-> Self
{
return response(
responseSerializer: Request.propertyListResponseSerializer(options: options),
completionHandler: completionHandler
)
}
}
| @@ -145,11 +145,13 @@ extension Request {
- returns: A data response serializer.
*/
public static func dataResponseSerializer() -> ResponseSerializer<NSData, NSError> {
- return ResponseSerializer { _, _, data, error in
+ return ResponseSerializer { _, response, data, error in
guard error == nil else { return .Failure(error!) }
- guard let validData = data where validData.length > 0 else {
- let failureReason = "Data could not be serialized. Input data was nil or zero length."
+ guard response?.statusCode ?? -1 != 204 else { return .Success(NSData()) } | Source/ResponseSerialization.swift | 0 | Swift | 0.286 | suggestion | 53 | 356 | 356 | false | Feature - Added 204 Support to Response Serializers | 889 | Alamofire/Alamofire | 41,690 | Swift | cnoon | cnoon |
// ResponseSerialization.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
// MARK: ResponseSerializer
/**
The type in which all response serializers must conform to in order to serialize a response.
*/
public protocol ResponseSerializerType {
/// The type of serialized object to be created by this `ResponseSerializerType`.
typealias SerializedObject
/// The type of error to be created by this `ResponseSerializer` if serialization fails.
typealias ErrorObject: ErrorType
/**
A closure used by response handlers that takes a request, response, data and error and returns a result.
*/
var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result<SerializedObject, ErrorObject> { get }
}
// MARK: -
/**
A generic `ResponseSerializerType` used to serialize a request, response, and data into a serialized object.
*/
public struct ResponseSerializer<Value, Error: ErrorType>: ResponseSerializerType {
/// The type of serialized object to be created by this `ResponseSerializer`.
public typealias SerializedObject = Value
/// The type of error to be created by this `ResponseSerializer` if serialization fails.
public typealias ErrorObject = Error
/**
A closure used by response handlers that takes a request, response, data and error and returns a result.
*/
public var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result<Value, Error>
/**
Initializes the `ResponseSerializer` instance with the given serialize response closure.
- parameter serializeResponse: The closure used to serialize the response.
- returns: The new generic response serializer instance.
*/
public init(serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result<Value, Error>) {
self.serializeResponse = serializeResponse
}
}
// MARK: - Default
extension Request {
/**
Adds a handler to be called once the request has finished.
- parameter queue: The queue on which the completion handler is dispatched.
- parameter completionHandler: The code to be executed once the request has finished.
- returns: The request.
*/
public func response(
queue queue: dispatch_queue_t? = nil,
completionHandler: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Void)
-> Self
{
delegate.queue.addOperationWithBlock {
dispatch_async(queue ?? dispatch_get_main_queue()) {
completionHandler(self.request, self.response, self.delegate.data, self.delegate.error)
}
}
return self
}
/**
Adds a handler to be called once the request has finished.
- parameter queue: The queue on which the completion handler is dispatched.
- parameter responseSerializer: The response serializer responsible for serializing the request, response,
and data.
- parameter completionHandler: The code to be executed once the request has finished.
- returns: The request.
*/
public func response<T: ResponseSerializerType>(
queue queue: dispatch_queue_t? = nil,
responseSerializer: T,
completionHandler: Response<T.SerializedObject, T.ErrorObject> -> Void)
-> Self
{
delegate.queue.addOperationWithBlock {
let result = responseSerializer.serializeResponse(
self.request,
self.response,
self.delegate.data,
self.delegate.error
)
dispatch_async(queue ?? dispatch_get_main_queue()) {
let response = Response<T.SerializedObject, T.ErrorObject>(
request: self.request,
response: self.response,
data: self.delegate.data,
result: result
)
completionHandler(response)
}
}
return self
}
}
// MARK: - Data
extension Request {
/**
Creates a response serializer that returns the associated data as-is.
- returns: A data response serializer.
*/
public static func dataResponseSerializer() -> ResponseSerializer<NSData, NSError> {
return ResponseSerializer { _, response, data, error in
guard error == nil else { return .Failure(error!) }
guard response?.statusCode ?? -1 != 204 else { return .Success(NSData()) }
guard let validData = data else {
let failureReason = "Data could not be serialized. Input data was nil."
let error = Error.errorWithCode(.DataSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
return .Success(validData)
}
}
/**
Adds a handler to be called once the request has finished.
- parameter completionHandler: The code to be executed once the request has finished.
- returns: The request.
*/
public func responseData(completionHandler: Response<NSData, NSError> -> Void) -> Self {
return response(responseSerializer: Request.dataResponseSerializer(), completionHandler: completionHandler)
}
}
// MARK: - String
extension Request {
/**
Creates a response serializer that returns a string initialized from the response data with the specified
string encoding.
- parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server
response, falling back to the default HTTP default character set, ISO-8859-1.
- returns: A string response serializer.
*/
public static func stringResponseSerializer(
var encoding encoding: NSStringEncoding? = nil)
-> ResponseSerializer<String, NSError>
{
return ResponseSerializer { _, response, data, error in
guard error == nil else { return .Failure(error!) }
guard response?.statusCode ?? -1 != 204 else { return .Success("") }
guard let validData = data else {
let failureReason = "String could not be serialized. Input data was nil."
let error = Error.errorWithCode(.StringSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
if let encodingName = response?.textEncodingName where encoding == nil {
encoding = CFStringConvertEncodingToNSStringEncoding(
CFStringConvertIANACharSetNameToEncoding(encodingName)
)
}
let actualEncoding = encoding ?? NSISOLatin1StringEncoding
if let string = String(data: validData, encoding: actualEncoding) {
return .Success(string)
} else {
let failureReason = "String could not be serialized with encoding: \(actualEncoding)"
let error = Error.errorWithCode(.StringSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
}
}
/**
Adds a handler to be called once the request has finished.
- parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the
server response, falling back to the default HTTP default character set,
ISO-8859-1.
- parameter completionHandler: A closure to be executed once the request has finished.
- returns: The request.
*/
public func responseString(
encoding encoding: NSStringEncoding? = nil,
completionHandler: Response<String, NSError> -> Void)
-> Self
{
return response(
responseSerializer: Request.stringResponseSerializer(encoding: encoding),
completionHandler: completionHandler
)
}
}
// MARK: - JSON
extension Request {
/**
Creates a response serializer that returns a JSON object constructed from the response data using
`NSJSONSerialization` with the specified reading options.
- parameter options: The JSON serialization reading options. `.AllowFragments` by default.
- returns: A JSON object response serializer.
*/
public static func JSONResponseSerializer(
options options: NSJSONReadingOptions = .AllowFragments)
-> ResponseSerializer<AnyObject, NSError>
{
return ResponseSerializer { _, response, data, error in
guard error == nil else { return .Failure(error!) }
guard response?.statusCode ?? -1 != 204 else { return .Success(NSNull()) }
guard let validData = data else {
let failureReason = "JSON could not be serialized. Input data was nil."
let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
do {
let JSON = try NSJSONSerialization.JSONObjectWithData(validData, options: options)
return .Success(JSON)
} catch {
return .Failure(error as NSError)
}
}
}
/**
Adds a handler to be called once the request has finished.
- parameter options: The JSON serialization reading options. `.AllowFragments` by default.
- parameter completionHandler: A closure to be executed once the request has finished.
- returns: The request.
*/
public func responseJSON(
options options: NSJSONReadingOptions = .AllowFragments,
completionHandler: Response<AnyObject, NSError> -> Void)
-> Self
{
return response(
responseSerializer: Request.JSONResponseSerializer(options: options),
completionHandler: completionHandler
)
}
}
// MARK: - Property List
extension Request {
/**
Creates a response serializer that returns an object constructed from the response data using
`NSPropertyListSerialization` with the specified reading options.
- parameter options: The property list reading options. `NSPropertyListReadOptions()` by default.
- returns: A property list object response serializer.
*/
public static func propertyListResponseSerializer(
options options: NSPropertyListReadOptions = NSPropertyListReadOptions())
-> ResponseSerializer<AnyObject, NSError>
{
return ResponseSerializer { _, response, data, error in
guard error == nil else { return .Failure(error!) }
guard response?.statusCode ?? -1 != 204 else { return .Success(NSNull()) }
guard let validData = data else {
let failureReason = "Property list could not be serialized. Input data was nil."
let error = Error.errorWithCode(.PropertyListSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
do {
let plist = try NSPropertyListSerialization.propertyListWithData(validData, options: options, format: nil)
return .Success(plist)
} catch {
return .Failure(error as NSError)
}
}
}
/**
Adds a handler to be called once the request has finished.
- parameter options: The property list reading options. `0` by default.
- parameter completionHandler: A closure to be executed once the request has finished. The closure takes 3
arguments: the URL request, the URL response, the server data and the result
produced while creating the property list.
- returns: The request.
*/
public func responsePropertyList(
options options: NSPropertyListReadOptions = NSPropertyListReadOptions(),
completionHandler: Response<AnyObject, NSError> -> Void)
-> Self
{
return response(
responseSerializer: Request.propertyListResponseSerializer(options: options),
completionHandler: completionHandler
)
}
}
| Yeah now I remember why I didn't do this...if response is nil then the `guard` will fail and it will return a `.Success` case which is definitely not what we want. I don't see an cleaner way to do it than I already have. Open to suggestions...
| // ResponseSerialization.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
// MARK: ResponseSerializer
/**
The type in which all response serializers must conform to in order to serialize a response.
*/
public protocol ResponseSerializerType {
/// The type of serialized object to be created by this `ResponseSerializerType`.
typealias SerializedObject
/// The type of error to be created by this `ResponseSerializer` if serialization fails.
typealias ErrorObject: ErrorType
/**
A closure used by response handlers that takes a request, response, data and error and returns a result.
*/
var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result<SerializedObject, ErrorObject> { get }
}
// MARK: -
/**
A generic `ResponseSerializerType` used to serialize a request, response, and data into a serialized object.
*/
public struct ResponseSerializer<Value, Error: ErrorType>: ResponseSerializerType {
/// The type of serialized object to be created by this `ResponseSerializer`.
public typealias SerializedObject = Value
/// The type of error to be created by this `ResponseSerializer` if serialization fails.
public typealias ErrorObject = Error
/**
A closure used by response handlers that takes a request, response, data and error and returns a result.
*/
public var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result<Value, Error>
/**
Initializes the `ResponseSerializer` instance with the given serialize response closure.
- parameter serializeResponse: The closure used to serialize the response.
- returns: The new generic response serializer instance.
*/
public init(serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result<Value, Error>) {
self.serializeResponse = serializeResponse
}
}
// MARK: - Default
extension Request {
/**
Adds a handler to be called once the request has finished.
- parameter queue: The queue on which the completion handler is dispatched.
- parameter completionHandler: The code to be executed once the request has finished.
- returns: The request.
*/
public func response(
queue queue: dispatch_queue_t? = nil,
completionHandler: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Void)
-> Self
{
delegate.queue.addOperationWithBlock {
dispatch_async(queue ?? dispatch_get_main_queue()) {
completionHandler(self.request, self.response, self.delegate.data, self.delegate.error)
}
}
return self
}
/**
Adds a handler to be called once the request has finished.
- parameter queue: The queue on which the completion handler is dispatched.
- parameter responseSerializer: The response serializer responsible for serializing the request, response,
and data.
- parameter completionHandler: The code to be executed once the request has finished.
- returns: The request.
*/
public func response<T: ResponseSerializerType>(
queue queue: dispatch_queue_t? = nil,
responseSerializer: T,
completionHandler: Response<T.SerializedObject, T.ErrorObject> -> Void)
-> Self
{
delegate.queue.addOperationWithBlock {
let result = responseSerializer.serializeResponse(
self.request,
self.response,
self.delegate.data,
self.delegate.error
)
dispatch_async(queue ?? dispatch_get_main_queue()) {
let response = Response<T.SerializedObject, T.ErrorObject>(
request: self.request,
response: self.response,
data: self.delegate.data,
result: result
)
completionHandler(response)
}
}
return self
}
}
// MARK: - Data
extension Request {
/**
Creates a response serializer that returns the associated data as-is.
- returns: A data response serializer.
*/
public static func dataResponseSerializer() -> ResponseSerializer<NSData, NSError> {
return ResponseSerializer { _, response, data, error in
guard error == nil else { return .Failure(error!) }
if let response = response where response.statusCode == 204 { return .Success(NSData()) }
guard let validData = data else {
let failureReason = "Data could not be serialized. Input data was nil."
let error = Error.errorWithCode(.DataSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
return .Success(validData)
}
}
/**
Adds a handler to be called once the request has finished.
- parameter completionHandler: The code to be executed once the request has finished.
- returns: The request.
*/
public func responseData(completionHandler: Response<NSData, NSError> -> Void) -> Self {
return response(responseSerializer: Request.dataResponseSerializer(), completionHandler: completionHandler)
}
}
// MARK: - String
extension Request {
/**
Creates a response serializer that returns a string initialized from the response data with the specified
string encoding.
- parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server
response, falling back to the default HTTP default character set, ISO-8859-1.
- returns: A string response serializer.
*/
public static func stringResponseSerializer(
var encoding encoding: NSStringEncoding? = nil)
-> ResponseSerializer<String, NSError>
{
return ResponseSerializer { _, response, data, error in
guard error == nil else { return .Failure(error!) }
if let response = response where response.statusCode == 204 { return .Success("") }
guard let validData = data else {
let failureReason = "String could not be serialized. Input data was nil."
let error = Error.errorWithCode(.StringSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
if let encodingName = response?.textEncodingName where encoding == nil {
encoding = CFStringConvertEncodingToNSStringEncoding(
CFStringConvertIANACharSetNameToEncoding(encodingName)
)
}
let actualEncoding = encoding ?? NSISOLatin1StringEncoding
if let string = String(data: validData, encoding: actualEncoding) {
return .Success(string)
} else {
let failureReason = "String could not be serialized with encoding: \(actualEncoding)"
let error = Error.errorWithCode(.StringSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
}
}
/**
Adds a handler to be called once the request has finished.
- parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the
server response, falling back to the default HTTP default character set,
ISO-8859-1.
- parameter completionHandler: A closure to be executed once the request has finished.
- returns: The request.
*/
public func responseString(
encoding encoding: NSStringEncoding? = nil,
completionHandler: Response<String, NSError> -> Void)
-> Self
{
return response(
responseSerializer: Request.stringResponseSerializer(encoding: encoding),
completionHandler: completionHandler
)
}
}
// MARK: - JSON
extension Request {
/**
Creates a response serializer that returns a JSON object constructed from the response data using
`NSJSONSerialization` with the specified reading options.
- parameter options: The JSON serialization reading options. `.AllowFragments` by default.
- returns: A JSON object response serializer.
*/
public static func JSONResponseSerializer(
options options: NSJSONReadingOptions = .AllowFragments)
-> ResponseSerializer<AnyObject, NSError>
{
return ResponseSerializer { _, response, data, error in
guard error == nil else { return .Failure(error!) }
if let response = response where response.statusCode == 204 { return .Success(NSNull()) }
guard let validData = data where validData.length > 0 else {
let failureReason = "JSON could not be serialized. Input data was nil or zero length."
let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
do {
let JSON = try NSJSONSerialization.JSONObjectWithData(validData, options: options)
return .Success(JSON)
} catch {
return .Failure(error as NSError)
}
}
}
/**
Adds a handler to be called once the request has finished.
- parameter options: The JSON serialization reading options. `.AllowFragments` by default.
- parameter completionHandler: A closure to be executed once the request has finished.
- returns: The request.
*/
public func responseJSON(
options options: NSJSONReadingOptions = .AllowFragments,
completionHandler: Response<AnyObject, NSError> -> Void)
-> Self
{
return response(
responseSerializer: Request.JSONResponseSerializer(options: options),
completionHandler: completionHandler
)
}
}
// MARK: - Property List
extension Request {
/**
Creates a response serializer that returns an object constructed from the response data using
`NSPropertyListSerialization` with the specified reading options.
- parameter options: The property list reading options. `NSPropertyListReadOptions()` by default.
- returns: A property list object response serializer.
*/
public static func propertyListResponseSerializer(
options options: NSPropertyListReadOptions = NSPropertyListReadOptions())
-> ResponseSerializer<AnyObject, NSError>
{
return ResponseSerializer { _, response, data, error in
guard error == nil else { return .Failure(error!) }
if let response = response where response.statusCode == 204 { return .Success(NSNull()) }
guard let validData = data where validData.length > 0 else {
let failureReason = "Property list could not be serialized. Input data was nil or zero length."
let error = Error.errorWithCode(.PropertyListSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
do {
let plist = try NSPropertyListSerialization.propertyListWithData(validData, options: options, format: nil)
return .Success(plist)
} catch {
return .Failure(error as NSError)
}
}
}
/**
Adds a handler to be called once the request has finished.
- parameter options: The property list reading options. `0` by default.
- parameter completionHandler: A closure to be executed once the request has finished. The closure takes 3
arguments: the URL request, the URL response, the server data and the result
produced while creating the property list.
- returns: The request.
*/
public func responsePropertyList(
options options: NSPropertyListReadOptions = NSPropertyListReadOptions(),
completionHandler: Response<AnyObject, NSError> -> Void)
-> Self
{
return response(
responseSerializer: Request.propertyListResponseSerializer(options: options),
completionHandler: completionHandler
)
}
}
| @@ -145,11 +145,13 @@ extension Request {
- returns: A data response serializer.
*/
public static func dataResponseSerializer() -> ResponseSerializer<NSData, NSError> {
- return ResponseSerializer { _, _, data, error in
+ return ResponseSerializer { _, response, data, error in
guard error == nil else { return .Failure(error!) }
- guard let validData = data where validData.length > 0 else {
- let failureReason = "Data could not be serialized. Input data was nil or zero length."
+ guard response?.statusCode ?? -1 != 204 else { return .Success(NSData()) } | Source/ResponseSerialization.swift | 0 | Swift | 0.571 | bug | 244 | 356 | 356 | false | Feature - Added 204 Support to Response Serializers | 889 | Alamofire/Alamofire | 41,690 | Swift | cnoon | cnoon |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.